Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81152 views
1
/**
2
* Copyright 2014, Facebook, Inc.
3
* All rights reserved.
4
*
5
* This source code is licensed under the BSD-style license found in the
6
* LICENSE file in the root directory of this source tree. An additional grant
7
* of patent rights can be found in the PATENTS file in the same directory.
8
*
9
* @providesModule accumulateInto
10
*/
11
12
"use strict";
13
14
var invariant = require('invariant');
15
16
/**
17
*
18
* Accumulates items that must not be null or undefined into the first one. This
19
* is used to conserve memory by avoiding array allocations, and thus sacrifices
20
* API cleanness. Since `current` can be null before being passed in and not
21
* null after this function, make sure to assign it back to `current`:
22
*
23
* `a = accumulateInto(a, b);`
24
*
25
* This API should be sparingly used. Try `accumulate` for something cleaner.
26
*
27
* @return {*|array<*>} An accumulation of items.
28
*/
29
30
function accumulateInto(current, next) {
31
invariant(
32
next != null,
33
'accumulateInto(...): Accumulated items must not be null or undefined.'
34
);
35
if (current == null) {
36
return next;
37
}
38
39
// Both are not empty. Warning: Never call x.concat(y) when you are not
40
// certain that x is an Array (x could be a string with concat method).
41
var currentIsArray = Array.isArray(current);
42
var nextIsArray = Array.isArray(next);
43
44
if (currentIsArray && nextIsArray) {
45
current.push.apply(current, next);
46
return current;
47
}
48
49
if (currentIsArray) {
50
current.push(next);
51
return current;
52
}
53
54
if (nextIsArray) {
55
// A bit too dangerous to mutate `next`.
56
return [current].concat(next);
57
}
58
59
return [current, next];
60
}
61
62
module.exports = accumulateInto;
63
64