flatMap.js.flow 709 B

1234567891011121314151617181920212223242526272829
  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. // Workaround to make older Flow versions happy
  7. const flatMapMethod = (Array.prototype: any).flatMap;
  8. /* eslint-disable no-redeclare */
  9. // $FlowFixMe
  10. const flatMap = flatMapMethod
  11. ? function(list, fn) {
  12. return flatMapMethod.call(list, fn);
  13. }
  14. : function(list, fn) {
  15. let result = [];
  16. for (const item of list) {
  17. const value = fn(item);
  18. if (Array.isArray(value)) {
  19. result = result.concat(value);
  20. } else {
  21. result.push(value);
  22. }
  23. }
  24. return result;
  25. };
  26. export default flatMap;