Skip to content

Instantly share code, notes, and snippets.

@cozyazure
Last active February 26, 2017 13:49
Show Gist options
  • Save cozyazure/bdea86b2027f7dcab99ac3c0357172de to your computer and use it in GitHub Desktop.
Save cozyazure/bdea86b2027f7dcab99ac3c0357172de to your computer and use it in GitHub Desktop.
A bunch of call back functions to apply to a bunch of arrays
// Write a function that takes an array and an iterator function and applies
// the function to each element in that array
//
// Note: each does not have a return value, but rather simply runs the
// iterator function over each item in the input collection.
//
// Example:
// each([1,2,3], function(val) { console.log(val*val); }) // output 1, 4, 9
var each = (array, iterator) => {
array.forEach(x => {
iterator(x);
});
};
// Using each, write a function that reduces an array or object to a single value by
// repetitively calling iterator(previousValue, item) for each item. previousValue should be
// the return value of the previous iterator call.
//
// You can pass in an initialValue that is passed to the first iterator
// call. If initialValue is not explicitly passed in, it should default to the
// first element in the collection.
//
// Example:
// var numbers = [1,2,3];
// var sum = reduce(numbers, function(total, number){
// return total + number;
// }, 0); // should be 6
var reduce = (array, iterator, memo) => {
each(array, function(item) {
memo = iterator(memo, item);
});
return memo;
};
// Using reduce, write a function that determine whether all of the elements match a truth test.
//
// Example:
// every([1,2,3,4,5], function(val){ return val < 10; }) // should return true
// every([1,2,3,4,5], function(val){ return val < 3; }) // should return false
var every = (array, truthTest) => {
return reduce(array, function(prev, current) {
return prev && truthTest(current);
}, true);
};
/////////////////////
// Test Case Zone ///
/////////////////////
/*Test Case for each*/
each([1, 2, 3], function(val) {
console.log(val * val);
});
/*Test Case for reduce*/
var numbers = [1, 2, 3, 4];
var sum = reduce(numbers, function(total, number) {
return total + number;
}, 0); // should be 6
console.log(sum);
/*Test Case for every*/
var a = every([1, 2, 3, 4, 5], function(val) {
return val < 10;
}); // should return true
var b = every([1, 2, 3, 4, 5], function(val) {
return val < 3;
}); // should return false
console.log('a', a);
console.log('b', b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment