Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81158 views
1
/**
2
* Copyright 2013-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 createArrayFrom
10
* @typechecks
11
*/
12
13
var toArray = require('toArray');
14
15
/**
16
* Perform a heuristic test to determine if an object is "array-like".
17
*
18
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
19
* Joshu replied: "Mu."
20
*
21
* This function determines if its argument has "array nature": it returns
22
* true if the argument is an actual array, an `arguments' object, or an
23
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
24
*
25
* It will return false for other array-like objects like Filelist.
26
*
27
* @param {*} obj
28
* @return {boolean}
29
*/
30
function hasArrayNature(obj) {
31
return (
32
// not null/false
33
!!obj &&
34
// arrays are objects, NodeLists are functions in Safari
35
(typeof obj == 'object' || typeof obj == 'function') &&
36
// quacks like an array
37
('length' in obj) &&
38
// not window
39
!('setInterval' in obj) &&
40
// no DOM node should be considered an array-like
41
// a 'select' element has 'length' and 'item' properties on IE8
42
(typeof obj.nodeType != 'number') &&
43
(
44
// a real array
45
Array.isArray(obj) ||
46
// arguments
47
('callee' in obj) ||
48
// HTMLCollection/NodeList
49
('item' in obj)
50
)
51
);
52
}
53
54
/**
55
* Ensure that the argument is an array by wrapping it in an array if it is not.
56
* Creates a copy of the argument if it is already an array.
57
*
58
* This is mostly useful idiomatically:
59
*
60
* var createArrayFrom = require('createArrayFrom');
61
*
62
* function takesOneOrMoreThings(things) {
63
* things = createArrayFrom(things);
64
* ...
65
* }
66
*
67
* This allows you to treat `things' as an array, but accept scalars in the API.
68
*
69
* If you need to convert an array-like object, like `arguments`, into an array
70
* use toArray instead.
71
*
72
* @param {*} obj
73
* @return {array}
74
*/
75
function createArrayFrom(obj) {
76
if (!hasArrayNature(obj)) {
77
return [obj];
78
} else if (Array.isArray(obj)) {
79
return obj.slice();
80
} else {
81
return toArray(obj);
82
}
83
}
84
85
module.exports = createArrayFrom;
86
87