forked from buxlabs/pure-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection.js
82 lines (72 loc) · 2.07 KB
/
collection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function append (collection, ...args) {
if (args.length === 0) {
return collection
}
if (typeof collection === 'string') {
return collection + args.join('')
} else if (Array.isArray(collection)) {
return [...collection, ...args]
}
throw new TypeError("[ERROR]: 'append' filter processes only strings or arrays")
}
function prepend (collection, ...args) {
if (args.length === 0) {
return collection
}
if (typeof collection === 'string') {
return args.join('') + collection
} else if (Array.isArray(collection)) {
return [...args, ...collection]
}
throw new TypeError("[ERROR]: 'prepend' filter processes only strings or arrays")
}
function reverse (collection) {
return Array.isArray(collection) ? collection.reverse() : [...collection].reverse().join('')
}
function size (collection) {
const type = Object.prototype.toString.call(collection).substr(8).replace(']', '')
if (type === 'Array' || type === 'String') return collection.length
if (type === 'Object') return Object.keys(collection).length
if (type === 'Map' || type === 'Set') return collection.size
}
function flatten (collection) {
if (Array.isArray(collection)) {
return collection.reduce((previous, current) => {
return previous.concat(Array.isArray(current) ? flatten(current) : current)
}, [])
}
const result = {}
for (const key in collection) {
if (typeof collection[key] === 'object') {
const deep = flatten(collection[key])
for (const prefix in deep) {
result[key + '.' + prefix] = deep[prefix]
}
} else {
result[key] = collection[key]
}
}
return result
}
function unflatten (collection) {
const result = {}
for (const key in collection) {
const parts = key.split('.')
let current = result
let property = '_'
for (let i = 0; i < parts.length; i++) {
current = current[property] || (current[property] = {})
property = parts[i]
}
current[property] = collection[key]
}
return result._
}
module.exports = {
append,
prepend,
reverse,
size,
flatten,
unflatten
}