ArrayHelpers.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * Compare two arrays or strings by performing strict equality check for each value.
  8. * @template T [T=any]
  9. * @param {ArrayLike<T>} a Array of values to be compared
  10. * @param {ArrayLike<T>} b Array of values to be compared
  11. * @returns {boolean} returns true if all the elements of passed arrays are strictly equal.
  12. */
  13. exports.equals = (a, b) => {
  14. if (a.length !== b.length) return false;
  15. for (let i = 0; i < a.length; i++) {
  16. if (a[i] !== b[i]) return false;
  17. }
  18. return true;
  19. };
  20. /**
  21. * Partition an array by calling a predicate function on each value.
  22. * @template T [T=any]
  23. * @param {Array<T>} arr Array of values to be partitioned
  24. * @param {(value: T) => boolean} fn Partition function which partitions based on truthiness of result.
  25. * @returns {[Array<T>, Array<T>]} returns the values of `arr` partitioned into two new arrays based on fn predicate.
  26. */
  27. exports.groupBy = (arr = [], fn) => {
  28. return arr.reduce(
  29. /**
  30. * @param {[Array<T>, Array<T>]} groups An accumulator storing already partitioned values returned from previous call.
  31. * @param {T} value The value of the current element
  32. * @returns {[Array<T>, Array<T>]} returns an array of partitioned groups accumulator resulting from calling a predicate on the current value.
  33. */
  34. (groups, value) => {
  35. groups[fn(value) ? 0 : 1].push(value);
  36. return groups;
  37. },
  38. [[], []]
  39. );
  40. };