Skip to content

Commit

Permalink
feat: add Nth item filter (#20)
Browse files Browse the repository at this point in the history
## 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, ...
```
  • Loading branch information
bahmutov authored Nov 18, 2021
1 parent 7758b5d commit 8377cda
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions cypress/integration/nth-spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// @ts-check
/// <reference types="cypress" />

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])
})
})
})
6 changes: 6 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 8377cda

Please sign in to comment.