const sum = ( xs ) : number => xs . reduce ( ( a , b ) => a + b , 0 ) ; /**
 * Helper for sorting the result
 */ const relevance = ( row ) => { return sum ( row ) * 1000000 + row . reduce ( ( a , b ) => Math . max ( a , b ) , Number . MIN_VALUE ) * 1000 + row . reduce ( ( prev , cur , idx , arr ) => prev + 2 ** ( arr . length - idx ) * cur , 0 ) ; } ; param a param b const byRelevance = ( a , b ) => relevance ( b ) - relevance ( a ) ; const appendAnotherDimension = ( totalDegree , oldSpacePoints ) : number [ ] [ ] => { const newSpacePoints = [ ] ; let i = 0 ; for ( ; i < oldSpacePoints . length ; i ++ ) { let value = 0 ; for ( ; value <= totalDegree ; ++ value ) { newSpacePoints . push ( oldSpacePoints [ i ] . concat ( [ value ] ) ) ; } } return newSpacePoints ; } ; const takeValidPoints = ( dimensions , totalDegree ) : number [ ] [ ] => { let points = [ [ ] ] ; for ( let dim = 1 ; dim <= dimensions ; ++ dim ) { points = appendAnotherDimension ( totalDegree , points ) ; } return points . filter ( ( point ) => sum ( point ) <= totalDegree ) ; } ; remarks param dimensions param degree returns export const makeExponentsArray = ( dimensions , degree ) : number [ ] [ ] => { if ( degree === 0 ) { return [ new Array ( dimensions ) . fill ( 0 ) ] ; } const stack = takeValidPoints ( dimensions , degree ) ; return stack . sort ( byRelevance ) ; } ; export default makeExponentsArray ;