flatMapArray.js.flow 985 B

12345678910111213141516171819202122232425262728293031323334353637
  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. * @flow
  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<TValue, TNext>(array: Array<TValue>, fn: (value: TValue, index: number) => Array<TNext>): Array<TNext> {
  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;