Skip to content

Commit

Permalink
feat(transducers): add page() xform, update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Feb 4, 2018
1 parent 596ed7a commit 855d803
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/transducers/README.md
Expand Up @@ -128,6 +128,27 @@ tx.reduce(
// }
```

### Pagination

```typescript
// extract only items for given page id & page length
[...tx.iterator(tx.page(0, 5), tx.range(12))]
// [ 0, 1, 2, 3, 4 ]

// when composing with other transducers
// it's most efficient to place `page()` early on in the chain
// that way only the page items will be further processed
[...tx.iterator(tx.comp(tx.page(1, 5), tx.map(x => x * 10)), tx.range(12))]
// [ 50, 60, 70, 80, 90 ]

// use `padLast()` to fill up missing values
[...tx.iterator(tx.comp(tx.page(2, 5), tx.padLast(5, "n/a")), tx.range(12))]
// [ 10, 11, 'n/a', 'n/a', 'n/a' ]

[...tx.iterator(tx.page(3, 5), rtx.ange(12))]
// []
```

### Multiplexing / parallel transducer application

`multiplex` and `multiplexObj` can be used to transform values in parallel
Expand Down
1 change: 1 addition & 0 deletions packages/transducers/src/index.ts
Expand Up @@ -59,6 +59,7 @@ export * from "./xform/multiplex";
export * from "./xform/multiplex-obj";
export * from "./xform/noop";
export * from "./xform/pad-last";
export * from "./xform/page";
export * from "./xform/partition-by";
export * from "./xform/partition-of";
export * from "./xform/partition-sort";
Expand Down
32 changes: 32 additions & 0 deletions packages/transducers/src/xform/page.ts
@@ -0,0 +1,32 @@
import { Transducer } from "../api";
import { comp } from "../func/comp";
import { drop } from "./drop";
import { take } from "./take";

/**
* Pagination helper. Returns transducer which extracts
* only items for given page number (and page length,
* default 10). When composing with other transducers,
* it's most efficient if `page()` is used prior to
* any heavy processing steps.
*
* ```
* [...iterator(page(0, 5), range(12))]
* // [ 0, 1, 2, 3, 4 ]
*
* [...iterator(page(1, 5), range(12))]
* // [ 5, 6, 7, 8, 9 ]
*
* [...iterator(page(2, 5), range(12))]
* // [ 10, 11 ]
*
* [...iterator(page(3, 5), range(12))]
* // []
* ```
*
* @param page
* @param pageLen
*/
export function page<T>(page: number, pageLen = 10): Transducer<T, T> {
return comp(drop(page * pageLen), take(pageLen));
}

0 comments on commit 855d803

Please sign in to comment.