diff --git a/packages/transducers/README.md b/packages/transducers/README.md index 82210a2f8c..e7bca67a5b 100644 --- a/packages/transducers/README.md +++ b/packages/transducers/README.md @@ -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 diff --git a/packages/transducers/src/index.ts b/packages/transducers/src/index.ts index 8e301c15c3..d9c9af5994 100644 --- a/packages/transducers/src/index.ts +++ b/packages/transducers/src/index.ts @@ -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"; diff --git a/packages/transducers/src/xform/page.ts b/packages/transducers/src/xform/page.ts new file mode 100644 index 0000000000..6c52eba193 --- /dev/null +++ b/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(page: number, pageLen = 10): Transducer { + return comp(drop(page * pageLen), take(pageLen)); +}