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(
    
  25.       'accumulate(...): Accumulated items must not be null or undefined.',
    
  26.     );
    
  27.   }
    
  28. 
    
  29.   if (current == null) {
    
  30.     return next;
    
  31.   }
    
  32. 
    
  33.   // Both are not empty. Warning: Never call x.concat(y) when you are not
    
  34.   // certain that x is an Array (x could be a string with concat method).
    
  35.   if (isArray(current)) {
    
  36.     /* $FlowFixMe[incompatible-return] if `current` is `T` and `T` an array,
    
  37.      * `isArray` might refine to the array element type of `T` */
    
  38.     return current.concat(next);
    
  39.   }
    
  40. 
    
  41.   if (isArray(next)) {
    
  42.     /* $FlowFixMe[incompatible-return] unsound if `next` is `T` and `T` an array,
    
  43.      * `isArray` might refine to the array element type of `T` */
    
  44.     return [current].concat(next);
    
  45.   }
    
  46. 
    
  47.   return [current, next];
    
  48. }
    
  49. 
    
  50. export default accumulate;