Skip to content

Instantly share code, notes, and snippets.

@70853n
Created October 1, 2020 10:13
Show Gist options
  • Save 70853n/cb1f131fb1f23023288dbbc52bb7a0a9 to your computer and use it in GitHub Desktop.
Save 70853n/cb1f131fb1f23023288dbbc52bb7a0a9 to your computer and use it in GitHub Desktop.
JavaScript range array and object with calculated keys
const upperRangeBoundry = 5;
const rangeSizedArray = [...Array(upperRangeBoundry)]
// -> (5) [undefined, undefined, undefined, undefined, undefined]
const rangeValuedArray = [...Array(upperRangeBoundry).keys()]
// -> (5) [0,1,2,3,4]
[...Array(8)].map((_, index, range) => 100 * index/range.length);
// -> (8) [0, 12.5, 25, 37.5, 50, 62.5, 75, 87.5]
[...Array(8+1)].map((_, index, range) => 100 * index/(range.length-1));
// -> (9) [0, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100]
[...Array(8+1).keys()].reduce((obj, _, index, range) => ({
...obj,
[100*index/(range.length-1)]: {}
}), {});
// -> { 0: {}, 12.5: {}, 25: {}, 37.5: {}, 50: {}, 62.5: {}, 75: {}, 87.5: {}, 100: {} }
[...Array(8+1).keys()].reduce((obj, _, index, range) => ({
...obj,
[`${100*index/(range.length-1)}%`]: {}
}), {});
// -> { 0%: {}, 12.5%: {}, 25%: {}, 37.5%: {}, 50%: {}, 62.5%: {}, 75%: {}, 87.5%: {}, 100%: {} }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment