I’m currently having trouble figuring out why both methods such as “addToSet()” and “removeFromSet()” isn’t working as expected. The situation here is that the methods doesn’t distinguish between “male” and “female” when called inside the “gender” scope. Basically, the “obj” keeps the “female” gender. When the “obj” identifier is used instead, it works like below:
var People_names = ['male 04/09/1982 (mother Daily Stacy): Doctor Brian the 2nd, John',
'male 20/02/1972 (mother Maria Doe): Doctor William, Billy',
'female 14/12/1986 (mother Stephanie Lopez): Doctor Hermes, Lisa',
'female 20/09/1904 (mother Stasha White): Doctor Bill, Ashley',
'male 10/07/1975 (mother Daily Brown): Doctor Brian the 2nd, Garth'];
var startsWith = function (start, end) {
return start.slice(start, end.length) === end;
};
var addToSet = function (set, values) {
for (var x = 0; x < values.length; x += 1) {
set[values[x]] = true;
}
}
var removeFromSet = function () {
for (var x = 0; x < values.length; x += 1) {
delete set[values[x]];
}
};
var extractNames = function (arr) {
var len = arr.length,
names = [],
list;
for (var x = 0; x < arr.length; x += 1) {
list = arr[x];
names[x] = list.slice(list.indexOf(',') + 2);
}
return names;
};
var gender = function (index, obj) {
obj = obj || {};
var x,
len = index.length,
extract = extractNames(index);
for (x = 0; x < len; x += 1) {
if (startsWith(index[x], 'male')) {
obj[extract[x]] = true;
}
}
return obj;
};
gender(People_names);
Both methods are called in the scope, which doesn’t separate both genders:
var gender = function (index, obj) {
obj = obj || {};
var x,
len = index.length,
extract = extractNames(index);
for (x = 0; x < len; x += 1) {
if (startsWith(index[x], 'male')) {
addToSet(obj, extract);
}
else if(startsWith(index[x], 'female')) {
removeFromSet(obj, extract);
}
}
return obj;
};
My code is similar to the original code, which came from “Eloquent JavaScript” by the way.
Can anyone help me with this problem?
Thanks