Skip to content

Commit ea6cd4b

Browse files
committed
finished callbacks.js
1 parent afae86b commit ea6cd4b

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

assignments/callbacks.js

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Create a callback function and invoke the function to test your work. You have been provided an example of a problem and a solution to see how this works with our items array. Study both the problem and the solution to figure out the rest of the problems.
22

3-
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
3+
const items = ["Pencil", "Notebook", "yo-yo", "Gum"];
44

55
/*
66
@@ -21,32 +21,89 @@ const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
2121
2222
*/
2323

24-
2524
function getLength(arr, cb) {
2625
// getLength passes the length of the array into the callback.
26+
return cb(arr);
2727
}
28+
console.log(
29+
getLength(items, function(array) {
30+
return array.length;
31+
})
32+
);
2833

2934
function last(arr, cb) {
3035
// last passes the last item of the array into the callback.
36+
return cb(arr[arr.length - 1]);
3137
}
38+
console.log(
39+
last(items, function(lastItem) {
40+
return lastItem;
41+
})
42+
);
3243

3344
function sumNums(x, y, cb) {
3445
// sumNums adds two numbers (x, y) and passes the result to the callback.
46+
return cb(x + y);
3547
}
48+
console.log(
49+
sumNums(1, 2, function(num) {
50+
return num;
51+
})
52+
);
3653

3754
function multiplyNums(x, y, cb) {
3855
// multiplyNums multiplies two numbers and passes the result to the callback.
56+
return cb(x * y);
3957
}
58+
console.log(
59+
multiplyNums(1, 2, function(num) {
60+
return num;
61+
})
62+
);
4063

4164
function contains(item, list, cb) {
4265
// contains checks if an item is present inside of the given array/list.
4366
// Pass true to the callback if it is, otherwise pass false.
67+
return cb(list.includes(item));
4468
}
69+
console.log(
70+
contains("Gum", items, function(bool) {
71+
return bool;
72+
})
73+
);
4574

4675
/* STRETCH PROBLEM */
76+
let listWithDuplicates = [
77+
"one",
78+
"one",
79+
"three",
80+
"two",
81+
"two",
82+
"three",
83+
"three",
84+
"five",
85+
"tree",
86+
"four",
87+
"five",
88+
"five",
89+
"five"
90+
];
4791

4892
function removeDuplicates(array, cb) {
4993
// removeDuplicates removes all duplicate values from the given array.
5094
// Pass the duplicate free array to the callback function.
5195
// Do not mutate the original array.
96+
return cb(
97+
array.reduce(function(acc, element) {
98+
if (!acc.includes(element)) {
99+
acc.push(element);
100+
}
101+
return acc;
102+
}, [])
103+
);
52104
}
105+
console.log(
106+
removeDuplicates(listWithDuplicates, function(array) {
107+
return array;
108+
})
109+
);

0 commit comments

Comments
 (0)