From 12f2441b2d9a35e6866465b78a7ecb3828b10a08 Mon Sep 17 00:00:00 2001 From: JanMalch <25508038+JanMalch@users.noreply.github.com> Date: Wed, 7 Oct 2020 08:47:30 +0200 Subject: [PATCH] Add factoryWithSeed snippet --- snippets/factoryWithSeed.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/factoryWithSeed.md diff --git a/snippets/factoryWithSeed.md b/snippets/factoryWithSeed.md new file mode 100644 index 000000000..1871680a3 --- /dev/null +++ b/snippets/factoryWithSeed.md @@ -0,0 +1,22 @@ +--- +title: factoryWithSeed +tags: array,beginner +--- + +Generates the given amount of objects based on the given factory, which receives a unique seed. + +- Creates a new array of size `amount`. +- Fills it with some value to be able to iterate over it via `map`. +- Uses `map`'s second argument, the index, as a seed for the factory. + +```js +const factoryWithSeed = (amount, factory) => + Array(amount) // create array with so many empty slots + .fill(0) // fill them to be able to iterate + .map((_, i) => factory(i)) // use index as seed +``` + +```js +const mockData = factoryWithSeed(5000, seed => ({ id: seed, name: randomAlphaNumeric(10) })); +// 5000 items with unique IDs +```