|
| 1 | +# cached-iterable |
| 2 | + |
| 3 | +`cached-iterable` exposes the `CachedItearble` class which implements the |
| 4 | +[iterable protocol][]. |
| 5 | + |
| 6 | +You can wrap any iterable in these classes to create a new iterable which |
| 7 | +caches the yielded elements. This is useful for iterating over an iterable many |
| 8 | +times without depleting it. |
| 9 | + |
| 10 | +[iterable protocol]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol |
| 11 | + |
| 12 | +## Installation |
| 13 | + |
| 14 | +`cached-iterable` can be used both on the client-side and the server-side. You |
| 15 | +can install it from the npm registry or use it as a standalone script (as the |
| 16 | +`CachedIterable` global). |
| 17 | + |
| 18 | + npm install cached-iterable |
| 19 | + |
| 20 | +## How to use |
| 21 | + |
| 22 | +```js |
| 23 | +import assert from "assert"; |
| 24 | +import {CachedIterable} from "cached-iterable"; |
| 25 | + |
| 26 | +function * countdown(i) { |
| 27 | + while (i--) { |
| 28 | + yield i; |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +let numbers = new CachedIterable(countdown(3)); |
| 33 | + |
| 34 | +// `numbers` can be iterated over multiple times. |
| 35 | +assert.deepEqual([...numbers], [3, 2, 1, 0]); |
| 36 | +assert.deepEqual([...numbers], [3, 2, 1, 0]); |
| 37 | +``` |
| 38 | + |
| 39 | +## Compatibility |
| 40 | + |
| 41 | +For legacy browsers, the `compat` build has been transpiled using Babel's [env |
| 42 | +preset][]. It requires the regenerator runtime provided by [babel-polyfill][]. |
| 43 | + |
| 44 | +```javascript |
| 45 | +import {CachedIterable} from 'cached-iterable/compat'; |
| 46 | +``` |
| 47 | + |
| 48 | +[env preset]: https://babeljs.io/docs/plugins/preset-env/ |
| 49 | +[babel-polyfill]: https://babeljs.io/docs/usage/polyfill/ |
0 commit comments