Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Created January 6, 2021 22:17
Show Gist options
  • Select an option

  • Save ryuheechul/b1eddb3bcc890f110ff94e95beec9245 to your computer and use it in GitHub Desktop.

Select an option

Save ryuheechul/b1eddb3bcc890f110ff94e95beec9245 to your computer and use it in GitHub Desktop.
get every possible case from ranges
// 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);
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