Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81158 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 toArray
10
* @typechecks
11
*/
12
13
var invariant = require('invariant');
14
15
/**
16
* Convert array-like objects to arrays.
17
*
18
* This API assumes the caller knows the contents of the data type. For less
19
* well defined inputs use createArrayFrom.
20
*
21
* @param {object|function|filelist} obj
22
* @return {array}
23
*/
24
function toArray(obj) {
25
var length = obj.length;
26
27
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
28
// old versions of Safari).
29
invariant(
30
!Array.isArray(obj) &&
31
(typeof obj === 'object' || typeof obj === 'function'),
32
'toArray: Array-like object expected'
33
);
34
35
invariant(
36
typeof length === 'number',
37
'toArray: Object needs a length property'
38
);
39
40
invariant(
41
length === 0 ||
42
(length - 1) in obj,
43
'toArray: Object should have keys for indices'
44
);
45
46
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
47
// without method will throw during the slice call and skip straight to the
48
// fallback.
49
if (obj.hasOwnProperty) {
50
try {
51
return Array.prototype.slice.call(obj);
52
} catch (e) {
53
// IE < 9 does not support Array#slice on collections objects
54
}
55
}
56
57
// Fall back to copying key by key. This assumes all keys have a value,
58
// so will not preserve sparsely populated inputs.
59
var ret = Array(length);
60
for (var ii = 0; ii < length; ii++) {
61
ret[ii] = obj[ii];
62
}
63
return ret;
64
}
65
66
module.exports = toArray;
67
68