flatMapArray.js 865 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. /**
  3. * Copyright (c) 2013-present, Facebook, Inc.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. * @typechecks
  9. */
  10. var push = Array.prototype.push;
  11. /**
  12. * Applies a function to every item in an array and concatenates the resulting
  13. * arrays into a single flat array.
  14. *
  15. * @param {array} array
  16. * @param {function} fn
  17. * @return {array}
  18. */
  19. function flatMapArray(array, fn) {
  20. var ret = [];
  21. for (var ii = 0; ii < array.length; ii++) {
  22. var result = fn.call(array, array[ii], ii);
  23. if (Array.isArray(result)) {
  24. push.apply(ret, result);
  25. } else if (result != null) {
  26. throw new TypeError('flatMapArray: Callback must return an array or null, ' + 'received "' + result + '" instead');
  27. }
  28. }
  29. return ret;
  30. }
  31. module.exports = flatMapArray;