main
js 47 lines 1.2 KB
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 import isArray from 'shared/isArray';
11
12 /**
13 * Accumulates items that must not be null or undefined.
14 *
15 * This is used to conserve memory by avoiding array allocations.
16 *
17 * @return {*|array<*>} An accumulation of items.
18 */
19 function accumulate<T>(
20 current: ?(T | Array<T>),
21 next: T | Array<T>,
22 ): T | Array<T> {
23 if (next == null) {
24 throw new Error('Accumulated items must not be null or undefined.');
25 }
26
27 if (current == null) {
28 return next;
29 }
30
31 // Both are not empty. Warning: Never call x.concat(y) when you are not
32 // certain that x is an Array (x could be a string with concat method).
33 if (isArray(current)) {
34 // $FlowFixMe[incompatible-use] `isArray` does not ensure array is mutable
35 return current.concat(next);
36 }
37
38 if (isArray(next)) {
39 /* $FlowFixMe[incompatible-return] unsound if `next` is `T` and `T` an array,
40 * `isArray` might refine to the array element type of `T` */
41 return [current].concat(next);
42 }
43
44 return [current, next];
45 }
46
47 export default accumulate;