flatMap.js.flow 709 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// @flow strict

declare function flatMap<T, U>(
  list: $ReadOnlyArray<T>,
  fn: (item: T, index: number) => $ReadOnlyArray<U> | U,
): Array<U>;

// Workaround to make older Flow versions happy
const flatMapMethod = (Array.prototype: any).flatMap;

/* eslint-disable no-redeclare */
// $FlowFixMe
const flatMap = flatMapMethod
  ? function(list, fn) {
      return flatMapMethod.call(list, fn);
    }
  : function(list, fn) {
      let result = [];
      for (const item of list) {
        const value = fn(item);
        if (Array.isArray(value)) {
          result = result.concat(value);
        } else {
          result.push(value);
        }
      }
      return result;
    };
export default flatMap;