flatMap.js.flow 656 B

12345678910111213141516171819202122232425262728
  1. // @flow strict
  2. declare function flatMap<T, U>(
  3. list: $ReadOnlyArray<T>,
  4. fn: (item: T, index: number) => $ReadOnlyArray<U> | U,
  5. ): Array<U>;
  6. const flatMapMethod = Array.prototype.flatMap;
  7. /* eslint-disable no-redeclare */
  8. // $FlowFixMe
  9. const flatMap = flatMapMethod
  10. ? function (list, fn) {
  11. return flatMapMethod.call(list, fn);
  12. }
  13. : function (list, fn) {
  14. let result = [];
  15. for (const item of list) {
  16. const value = fn(item);
  17. if (Array.isArray(value)) {
  18. result = result.concat(value);
  19. } else {
  20. result.push(value);
  21. }
  22. }
  23. return result;
  24. };
  25. export default flatMap;