SHARE
TWEET

generators.js

a guest Apr 18th, 2019 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Reduce function for iterables.
  3.  *
  4.  * @see https://github.com/jb55/reduce-iterator
  5.  *
  6.  * @param xs
  7.  * @param reducer
  8.  * @param acc
  9.  * @returns {*}
  10.  */
  11. function reduceIterator (xs, reducer, acc) {
  12.     let first = true;
  13.     let prev = acc;
  14.  
  15.     for (let x of xs) {
  16.         if (first) {
  17.             first = false;
  18.             if (arguments.length < 3) {
  19.                 prev = x;
  20.                 continue;
  21.             }
  22.         }
  23.         prev = reducer(prev, x)
  24.     }
  25.  
  26.     return prev;
  27. }
  28.  
  29. /**
  30.  * Pipes an iterable through a variadric functions array.
  31.  *
  32.  * @param fns
  33.  * @returns {function(*=): *}
  34.  */
  35. export const pipe = (...fns) => function (iterable) {
  36.     return reduceIterator(fns, (result, fn) => fn(result), iterable);
  37. };
  38.  
  39. /**
  40.  * Takes a number of elements from an iterable.
  41.  *
  42.  * @param {Number} n Number of elements
  43.  * @returns {Function} Generator
  44.  */
  45. export const take = n => function* (iterable) {
  46.     let i = 0;
  47.  
  48.     for (let item of iterable) {
  49.         if (i < n) {
  50.             yield item;
  51.         }
  52.  
  53.         i++;
  54.     }
  55. };
  56.  
  57. /**
  58.  * Takes elements from an iterable that match the given predicate.
  59.  *
  60.  * @param {Function} predicate
  61.  * @returns {Function}
  62.  */
  63. export const takeIf = predicate => function* (iterable) {
  64.     for (let item of iterable) {
  65.         if (predicate(item)) {
  66.             yield item;
  67.         }
  68.     }
  69. };
  70.  
  71. /**
  72.  * Skips a number of elements in an iterable and yields the rest.
  73.  *
  74.  * @param {Number} n Number of elements
  75.  * @returns {Function} Generator
  76.  */
  77. export const skip = n => function* (iterable) {
  78.     let i = 0;
  79.  
  80.     for (let item of iterable) {
  81.         if (i >= n) {
  82.             yield item;
  83.         }
  84.  
  85.         i++;
  86.     }
  87. };
  88.  
  89. /**
  90.  * Skips items of an iterable that match the given predicate.
  91.  *
  92.  * @param {Function} predicate
  93.  * @returns {Function} Generator
  94.  */
  95. export const skipIf = predicate => function* (iterable) {
  96.     for (let item of iterable) {
  97.         if (!predicate(item)) {
  98.             yield item;
  99.         }
  100.     }
  101. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top