Created
January 6, 2021 22:17
-
-
Save ryuheechul/b1eddb3bcc890f110ff94e95beec9245 to your computer and use it in GitHub Desktop.
get every possible case from ranges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // get every possible case from ranges | |
| const ranges = { | |
| a: [1, 2, 3], | |
| b: [4, 5], | |
| c: [6, 7, 8], | |
| }; | |
| console.log('ranges:'); | |
| console.log(ranges); | |
| const f = Object.keys(ranges).reduce((acc, key) => { | |
| const range = ranges[key]; | |
| return acc.map(a => | |
| range.map(n => | |
| Object.assign({...a}, {[key]: n }) | |
| ) | |
| ).flat(); | |
| }, [{}]); | |
| console.log('functional way:'); | |
| console.log(f); | |
| let result = [{}]; | |
| for (const k in ranges) { | |
| const v = ranges[k]; | |
| let bucket = []; | |
| for (const i in result) { | |
| const r = result[i]; | |
| for (const j in v) { | |
| const value = v[j]; | |
| bucket.push(Object.assign({...r}, {[k]: value})) | |
| } | |
| } | |
| result = bucket; | |
| } | |
| console.log('imperative way:'); | |
| console.log(result); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ranges: | |
| { a: [ 1, 2, 3 ], b: [ 4, 5 ], c: [ 6, 7, 8 ] } | |
| functional way: | |
| [ | |
| { a: 1, b: 4, c: 6 }, { a: 1, b: 4, c: 7 }, | |
| { a: 1, b: 4, c: 8 }, { a: 1, b: 5, c: 6 }, | |
| { a: 1, b: 5, c: 7 }, { a: 1, b: 5, c: 8 }, | |
| { a: 2, b: 4, c: 6 }, { a: 2, b: 4, c: 7 }, | |
| { a: 2, b: 4, c: 8 }, { a: 2, b: 5, c: 6 }, | |
| { a: 2, b: 5, c: 7 }, { a: 2, b: 5, c: 8 }, | |
| { a: 3, b: 4, c: 6 }, { a: 3, b: 4, c: 7 }, | |
| { a: 3, b: 4, c: 8 }, { a: 3, b: 5, c: 6 }, | |
| { a: 3, b: 5, c: 7 }, { a: 3, b: 5, c: 8 } | |
| ] | |
| imperative way: | |
| [ | |
| { a: 1, b: 4, c: 6 }, { a: 1, b: 4, c: 7 }, | |
| { a: 1, b: 4, c: 8 }, { a: 1, b: 5, c: 6 }, | |
| { a: 1, b: 5, c: 7 }, { a: 1, b: 5, c: 8 }, | |
| { a: 2, b: 4, c: 6 }, { a: 2, b: 4, c: 7 }, | |
| { a: 2, b: 4, c: 8 }, { a: 2, b: 5, c: 6 }, | |
| { a: 2, b: 5, c: 7 }, { a: 2, b: 5, c: 8 }, | |
| { a: 3, b: 4, c: 6 }, { a: 3, b: 4, c: 7 }, | |
| { a: 3, b: 4, c: 8 }, { a: 3, b: 5, c: 6 }, | |
| { a: 3, b: 5, c: 7 }, { a: 3, b: 5, c: 8 } | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment