Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/array-back/index.mjs
1126 views
1
/**
2
* Takes any input and guarantees an array back.
3
*
4
* - Converts array-like objects (e.g. `arguments`, `Set`) to a real array.
5
* - Converts `undefined` to an empty array.
6
* - Converts any another other, singular value (including `null`, objects and iterables other than `Set`) into an array containing that value.
7
* - Ignores input which is already an array.
8
*
9
* @module array-back
10
* @example
11
* > const arrayify = require('array-back')
12
*
13
* > arrayify(undefined)
14
* []
15
*
16
* > arrayify(null)
17
* [ null ]
18
*
19
* > arrayify(0)
20
* [ 0 ]
21
*
22
* > arrayify([ 1, 2 ])
23
* [ 1, 2 ]
24
*
25
* > arrayify(new Set([ 1, 2 ]))
26
* [ 1, 2 ]
27
*
28
* > function f(){ return arrayify(arguments); }
29
* > f(1,2,3)
30
* [ 1, 2, 3 ]
31
*/
32
33
function isObject (input) {
34
return typeof input === 'object' && input !== null
35
}
36
37
function isArrayLike (input) {
38
return isObject(input) && typeof input.length === 'number'
39
}
40
41
/**
42
* @param {*} - The input value to convert to an array
43
* @returns {Array}
44
* @alias module:array-back
45
*/
46
function arrayify (input) {
47
if (Array.isArray(input)) {
48
return input
49
}
50
51
if (input === undefined) {
52
return []
53
}
54
55
if (isArrayLike(input) || input instanceof Set) {
56
return Array.from(input)
57
}
58
59
return [ input ]
60
}
61
62
export default arrayify
63
64