-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_createPeople.js
49 lines (39 loc) · 1.41 KB
/
app_createPeople.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
'use strict';
/*
Build the following structure (not by hand):
var people = [
{name: 'Joe', age: 22, city: 'New York City', gender: 'male'},
{name: 'Jane', age: 85, city: 'Las Vegas', gender: 'female'},
{name: 'Jack', age: 55, city: 'London', gender: 'male'},
];
*/
var attrs = 'name age city gender';
var values = [
['Joe', 22, 'New York City', 'male'],
['Jane', 85, 'Las Vegas', 'female'],
['Jack', 55, 'London', 'male']
];
var people = [];
// Create new inheritable function for setting the attribute fields and values
Person.prototype.selfInitializer = function (attributeNames, attributeValues) {
// Create array from given string
var attributeNameCollection = attributeNames.split(' ');
// Create and set the attributes fields
attributeNameCollection.forEach((current, index) => {
this[current] = attributeValues[index];
});
}
// Person object constructor
function Person(attributeNames, attributeValues) {
// Initialize Person attributes with own prototype function
this.selfInitializer(attributeNames, attributeValues);
}
// Create Person instances with given values into people array
function createPeople(attributeNames, attributeValues) {
for (var i = 0; i < attributeValues.length; i++) {
people.push(new Person(attributeNames, attributeValues[i]));
}
}
// Start application
createPeople(attrs, values);
console.log('Final result: ', people);