summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorEuAndreh <eu@euandre.org>2024-03-20 11:42:08 -0300
committerEuAndreh <eu@euandre.org>2024-03-20 11:42:08 -0300
commit139b9ff653e1a1b9c316cb5651f220c687f11895 (patch)
treea7a2eafd64dc31828ef1313910d735e7ee5756ee /src
parenttests/rand.mjs: Add MersenneTwister random number generator (diff)
downloadpapod-139b9ff653e1a1b9c316cb5651f220c687f11895.tar.gz
papod-139b9ff653e1a1b9c316cb5651f220c687f11895.tar.xz
src/utils.mjs: Add take() and range()
Diffstat (limited to 'src')
-rw-r--r--src/utils.mjs40
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;
+ }
+ }
+};