main
js 32 lines 996 Bytes
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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 * @flow
8 */
9
10 /**
11 * @param {array} arr an "accumulation" of items which is either an Array or
12 * a single item. Useful when paired with the `accumulate` module. This is a
13 * simple utility that allows us to reason about a collection of items, but
14 * handling the case when there is exactly one item (and we do not need to
15 * allocate an array).
16 * @param {function} cb Callback invoked with each element or a collection.
17 * @param {?} [scope] Scope used as `this` in a callback.
18 */
19 function forEachAccumulated<T>(
20 arr: ?(Array<T> | T),
21 cb: (elem: T) => void,
22 scope: ?any,
23 ) {
24 if (Array.isArray(arr)) {
25 // $FlowFixMe[incompatible-type] if `T` is an array, `cb` cannot be called
26 arr.forEach(cb, scope);
27 } else if (arr) {
28 cb.call(scope, arr);
29 }
30 }
31
32 export default forEachAccumulated;