-
Notifications
You must be signed in to change notification settings - Fork 0
/
objectMethods.js
111 lines (88 loc) · 1.94 KB
/
objectMethods.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
let me = {
firstName: 'Will',
};
let catman = {
firstName: 'Rocky',
lastName: 'Da Cat',
};
let dog = {
firstName: 'Rosie',
lastName: 'The Dog',
};
let fatcat = {
firstName: 'Boston',
lastName: 'Da Lazy Cat',
};
me.lastName = 'Rossen';
function fullName(person) {
console.log(person.firstName + ' ' + person.lastName);
}
function rollCall(collection) {
collection.forEach(fullName);
}
let people = {
collection: [],
lastIndexUsed: -1,
fullName: function(person) {
console.log(person.firstName + ' ' + person.lastName);
},
rollCall: function() {
this.collection.forEach(people.fullName);
},
};
//people.rollCall();
people.add = function(person) {
if (this.isInValidPerson(person)) {
return;
}
this.lastIndexUsed += 1;
person.id = this.lastIndexUsed;
this.collection.push(person);
};
people.getIndex = function(person) {
let index = -1;
this.collection.forEach(function(comparator, i) {
if (comparator.firstName === person.firstName &&
comparator.lastName === person.lastName) {
index = i;
}
});
return index;
};
people.remove = function(person) {
let index;
if (!this.isInValidPerson(person)) {
return;
}
index = this.getIndex(person);
if (index === -1) {
return;
}
this.collection.splice(index, 1);
};
people.isInValidPerson = function(person) {
return typeof person.firstName !== 'string' || typeof person.lastName !== 'string';
};
people.get = function(person) {
if (this.isInValidPerson(person)) {
return;
}
return this.collection[this.getIndex(person)];
};
people.update = function(person) {
if (this.isInValidPerson(person)) {
return;
}
let existingPersonId = this.getIndex(person);
if (existingPersonId === -1) {
this.add(person);
} else {
this.collection[existingPersonId] = person;
}
};
people.add(fatcat);
people.add(me);
people.add(catman);
people.add(dog);
people.rollCall();
console.log(people.get(catman));