Objective/s:
- To broaden knowledge and be comfortable in using Callbacks
For this assignment, you will not use any Javascript built-in functions, but amazingly "you" will create them from scratch! Imagine that those built-in functions are not yet released and you are not allowed to use like map(), etc..
Create a function called foreach
where the following code would work the way described below. Submit your assignment by attaching JS file.
//1
let result = foreach([1,2,3,4,5], function(num) { return num*2; });
console.log(result); //this should log [2,4,6,8,10]
//2
result = foreach([1,2,3,"v88", "training"], function(val) {
if(typeof(val) === 'number') {
return 0;
}
else {
return val;
}
});
console.log(result); //this should log [0,0,0,"v88","training"];
//3
result = foreach([1,2,3,"hello"], function(val) { return typeof(val); });
console.log(result); //this should log ["number", "number", "number", "string"];
Note how for the second foreach callback function, for a simple if/else statement, we can also use a ternary operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
If a ternary operator is used, above code could be simplified as follows:
//1
let result = foreach([1,2,3,4,5], function(num) { return num*2; });
console.log(result); //this should log [2,4,6,8,10]
//2
result = foreach([1,2,3,"v88", "training"], function(val) {
return ( (typeof(val) === 'number') ? 0 : val);
});
console.log(result); //this should log [0,0,0,"v88","training"];
//3
result = foreach([1,2,3,"hello"], function(val) { return typeof(val); });
console.log(result); //this should log ["number", "number", "number", "string"];
Crea...