From 5adaf7ba4ec9cb77b2afa0ad33c41d659ea93666 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 20 Jan 2022 19:31:40 +0200 Subject: [PATCH] Add 2 new generator snippets --- snippets/generateUntil.md | 28 ++++++++++++++++++++++++++++ snippets/generateWhile.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 snippets/generateUntil.md create mode 100644 snippets/generateWhile.md diff --git a/snippets/generateUntil.md b/snippets/generateUntil.md new file mode 100644 index 000000000..39ce4870a --- /dev/null +++ b/snippets/generateUntil.md @@ -0,0 +1,28 @@ +--- +title: generateUntil +tags: function,generator,advanced +firstSeen: 2022-01-21T05:00:00-04:00 +--- + +Creates a generator, that keeps producing new values until the given condition is met. + +- Initialize the current `val` using the `seed` value. +- Use a `while` loop to iterate while the `condition` function called with the current `val` returns `false`. +- Use `yield` to return the current `val` and optionally receive a new seed value, `nextSeed`. +- Use the `next` function to calculate the next value from the current `val` and the `nextSeed`. + +```js +const generateUntil = function* (seed, condition, next) { + let val = seed; + let nextSeed = null; + while (!condition(val)) { + nextSeed = yield val; + val = next(val, nextSeed); + } + return val; +}; +``` + +```js +[...generateUntil(1, v => v > 5, v => ++v)]; // [1, 2, 3, 4, 5] +``` diff --git a/snippets/generateWhile.md b/snippets/generateWhile.md new file mode 100644 index 000000000..123183362 --- /dev/null +++ b/snippets/generateWhile.md @@ -0,0 +1,28 @@ +--- +title: generateWhile +tags: function,generator,advanced +firstSeen: 2022-01-21T05:00:00-04:00 +--- + +Creates a generator, that keeps producing new values as long as the given condition is met. + +- Initialize the current `val` using the `seed` value. +- Use a `while` loop to iterate while the `condition` function called with the current `val` returns `true`. +- Use `yield` to return the current `val` and optionally receive a new seed value, `nextSeed`. +- Use the `next` function to calculate the next value from the current `val` and the `nextSeed`. + +```js +const generateWhile = function* (seed, condition, next) { + let val = seed; + let nextSeed = null; + while (condition(val)) { + nextSeed = yield val; + val = next(val, nextSeed); + } + return val; +}; +``` + +```js +[...generateWhile(1, v => v <= 5, v => ++v)]; // [1, 2, 3, 4, 5] +```