flatMapArray.js 871 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. *
  9. * @typechecks
  10. */
  11. var push = Array.prototype.push;
  12. /**
  13. * Applies a function to every item in an array and concatenates the resulting
  14. * arrays into a single flat array.
  15. *
  16. * @param {array} array
  17. * @param {function} fn
  18. * @return {array}
  19. */
  20. function flatMapArray(array, fn) {
  21. var ret = [];
  22. for (var ii = 0; ii < array.length; ii++) {
  23. var result = fn.call(array, array[ii], ii);
  24. if (Array.isArray(result)) {
  25. push.apply(ret, result);
  26. } else if (result != null) {
  27. throw new TypeError('flatMapArray: Callback must return an array or null, ' + 'received "' + result + '" instead');
  28. }
  29. }
  30. return ret;
  31. }
  32. module.exports = flatMapArray;