diff options
Diffstat (limited to 'src/utils.mjs')
-rw-r--r-- | src/utils.mjs | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/utils.mjs b/src/utils.mjs index 9a600e7..19c8e37 100644 --- a/src/utils.mjs +++ b/src/utils.mjs @@ -58,3 +58,43 @@ export const first = a => a[0]; export const rest = a => a.slice(1); export const butlast = a => a.slice(a, a.length - 1); export const last = a => a[a.length - 1]; + +export const take = function*(n, gen) { + let i = 0n; + for (const x of gen) { + if (i >= n) { + break; + } + i++; + yield x; + } +}; + +export const range = function*(x, y, step = 1n) { + if (x === undefined) { + let i = 0n; + while (true) { + yield i++; + } + } + const [from, to] = y === undefined ? + [0n, x] : + [x, y]; + const fromn = BigInt(from); + const ton = BigInt(to); + const stepn = BigInt(step); + if (stepn === 0n) { + while (true) { + yield fromn; + } + } + if (step < 0n) { + for (let i = fromn; i > ton; i+= stepn) { + yield i; + } + } else { + for (let i = fromn; i < ton; i += stepn) { + yield i; + } + } +}; |