Skip to content

Instantly share code, notes, and snippets.

@dungsaga
Last active April 7, 2023 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dungsaga/d556afc300803f04a34922a49ebd0641 to your computer and use it in GitHub Desktop.
Save dungsaga/d556afc300803f04a34922a49ebd0641 to your computer and use it in GitHub Desktop.
integer list generator in JS
// while reading "Why List Comprehension is Bad" (http://xahlee.info/comp/list_comprehension.html),
// I notice that JS don't have integer list generator like 0..9 or range(0,9)
// I wanna see if a one-liner can generate 1 list of integer i where 0 <= i < 9
// ref: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
// benchmark: https://jsbench.me/tykijeavk9/1 (from https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n/65244361#65244361)
// using generator
function*(){let i=0;while(i<9)yield i++}()
function*(i=0){while(i<9)yield i++}()
Array(9).keys()
[...'-'.repeat(9)].keys()
// using array (so it's easier to chain map, filter, ...)
Array(9).fill().map((v,i)=>i)
Array.from({length:9},(v,i)=>i)
Array.from(Array(9),(v,i)=>i)
Array.from(Array(9).keys())
[...Array(9)].map((v,i)=>i)
[...Array(9).keys()]
Array(9).map((v,i)=>i) // !! Wrong, map doesn't work with sparse array
[...'-'.repeat(9)].map((v,i)=>i)
'-'.repeat(9).split('').map((v,i)=>i)
// using lodash :D
_.range(9)
_.range(9, 99) // 9..99
_.range(0, 30, 5) // [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1) // [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
// using generator on class Number (inspired by https://stackoverflow.com/questions/36947847/how-to-generate-range-of-numbers-from-0-to-n-in-es2015-only/51114450#51114450)
Number.prototype[Symbol.iterator]=function*(i=0){while(i<this)yield i++}
[...9]
// if we want the range 9..99
Array(99 - 9).fill(9).map((v, i) => v + i)
Array(99 - 9).fill().map((v, i) => 9 + i)
Array.from(Array(99 - 9),(v, i) => 9 + i)
Array(99 - 9).map((v, i) => 9 + i) // !! Wrong, map doesn't work with sparse array
[...Array(99).keys()].slice(9)
[...Array(99 - 9)].map((v,i) => 9 + i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment