flatMapArray.js.flow 882 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule flatMapArray
  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;