-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (79 loc) · 2.5 KB
/
index.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
83
84
85
class GroupIterator {
constructor(groupThis){
this.group = groupThis.group
this.index = 0
this.last = groupThis.group.length-1
}
next () {
if(this.index > this.last) return {done: true}
this.index = this.index + 1
return {value: this.group[this.index - 1], done: false}
}
}
class HandyCollection {
constructor (options){
this.group = []
this.unique = options.unique
this.isArray = options.isArray
this.options = options
}
push(value){
if(this.unique) {
if(!this.group.includes(value)) this.group.push(value)
} else {
this.group.push(value)
}
}
setGroup(arr){
this.group = arr
}
delete(value){
this.group = this.group.filter((item) => item !==value)
}
has(value){
return this.group.includes(value)
}
get size(){
return this.group.length
}
filter(callbackOrPredicate) {
const isCallback = typeof callbackOrPredicate === 'function'
const copyCollection = new HandyCollection(this.options)
if(this.isArray){
const filteredCollection = this.group.filter(isCallback ? callbackOrPredicate : (item) => item !== callbackOrPredicate)
copyCollection.setGroup(filteredCollection)
} else {
const filteredCollection = []
this.group.forEach((obj) => {
if((Object.keys(obj)[0] === Object.keys(callbackOrPredicate)[0]) && obj[Object.keys(obj)[0]] == callbackOrPredicate[Object.keys(callbackOrPredicate)[0]]){
return
} else {
filteredCollection.push(obj)
copyCollection.setGroup(filteredCollection)
}
})
}
return copyCollection
}
static create (collection, options={unique:false}) {
const isArray = Array.isArray(collection)
const newGroup = new HandyCollection({...options, isArray})
if(isArray){
for (let item of collection) newGroup.push(item)
} else {
Object.keys(collection).map(key => {
newGroup.push({[key]: collection[key]})
})
}
return newGroup
}
map(callback){
this.group.map((item)=> callback(item))
}
[Symbol.iterator] () {
return new GroupIterator(this)
};
}
const newArr = HandyCollection.create({a: 1, b:2})
const test = newArr.filter()
console.log('test', test)