From 8377cda0a57b72738bfad39cd2d09f034e62b320 Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Thu, 18 Nov 2021 09:48:12 -0500 Subject: [PATCH] feat: add Nth item filter (#20) ## Every Nth item You can quickly take every Nth item from an array ```js it.each(items, N)(...) ``` This is the same as taking the index of the item (zero-based) and doing `k % N === 0` ```js const items = [1, 2, 3, 4, 5, 6, ...] it.each(items, 3)(...) // tests item 1, 4, 7, ... ``` --- README.md | 16 ++++++++++++++++ cypress/integration/nth-spec.js | 21 +++++++++++++++++++++ src/index.js | 6 ++++++ 3 files changed, 43 insertions(+) create mode 100644 cypress/integration/nth-spec.js diff --git a/README.md b/README.md index c784e26..7516cd0 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,22 @@ it.each([ See [cypress/integration/title-function.js](./cypress/integration/ title-function.js) for more examples +## Every Nth item + +You can quickly take every Nth item from an array + +```js +it.each(items, N)(...) +``` + +This is the same as taking the index of the item (zero-based) and doing `k % N === 0` + +```js +const items = [1, 2, 3, 4, 5, 6, ...] +it.each(items, 3)(...) +// tests item 1, 4, 7, ... +``` + ## Chunking There is a built-in chunking helper in `describe.each` and `it.each` to only take a subset of the items. For example, to split all items into 3 chunks, and take the middle one, use diff --git a/cypress/integration/nth-spec.js b/cypress/integration/nth-spec.js new file mode 100644 index 0000000..1cc41c8 --- /dev/null +++ b/cypress/integration/nth-spec.js @@ -0,0 +1,21 @@ +// @ts-check +/// + +import '../../src' + +describe('nth item', () => { + const items = [1, 2, 3, 4] + + context('every 2nd', () => { + // take every 2nd item, same as taking the item's zero-index module 2 + it.each(items, 2)('every 2nd item %K', (x) => { + expect(x, '1 or 3').to.be.oneOf([1, 3]) + }) + }) + + context('every 3nd', () => { + it.each(items, 3)('every 3nd item %K', (x) => { + expect(x, '1 or 4').to.be.oneOf([1, 4]) + }) + }) +}) diff --git a/src/index.js b/src/index.js index c06c522..0a8b29d 100644 --- a/src/index.js +++ b/src/index.js @@ -66,6 +66,12 @@ if (!it.each) { if (typeof totalChunks === 'number' && typeof chunkIndex === 'number') { // split all items into N chunks and take just a single chunk values = getChunk(values, totalChunks, chunkIndex) + } else if ( + typeof totalChunks === 'number' && + typeof chunkIndex === 'undefined' + ) { + // take every Nth item + values = values.filter((_, k) => k % totalChunks === 0) } values.forEach(function (value, k) {