Skip to content

Instantly share code, notes, and snippets.

@walkermatt
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkermatt/92f42fd076b8d750007e to your computer and use it in GitHub Desktop.
Save walkermatt/92f42fd076b8d750007e to your computer and use it in GitHub Desktop.
Toy map / reduce functions in JavaScript
// Define reduce, fn and list are required, init is an optional initial value
// which will be passed to fn with the first item in list
function reduce(fn, list, init) {
var val = init,
start = 0;
if (val === undefined) {
if (list.length > 1) {
val = list[0];
start = 1;
} else {
return list[0];
}
}
for (var i = start, item; i < list.length; i++) {
item = list[i];
val = fn(val, item);
}
return val;
}
// Sum all numbers
reduce(function(a, b) {return a + b}, [1, 2, 3]); // => 6
// Sum all numbers to 10
reduce(function(a, b) {return a + b}, [1, 2, 3], 10); // => 16
// Multiply all numbers
reduce(function(a, b) {return a * b}, [1, 2, 3], 10); // => 60
// Passing a single value simply returns it
reduce(function(a, b) {return a + b}, [1]); // => 1
// Define map based on reduce
function map(fn, list) {
return reduce(function(a, b) {
return a.concat(fn(b));
}, list, []);
}
// Double each number
map(function(a) {return a * 2}, [1, 2, 3]); // => [2, 4, 6]
// Each number to the power of 2
map(function(a) {return Math.pow(a, 2)}, [1, 2, 3]); // => [1, 4, 9]
// Define filter based on reduce
function filter(fn, list) {
return reduce(function(a, b) {
var result = fn(b);
if (result) {
return a.concat(b);
} else {
return a;
}
}, list, []);
}
// Numbers less than two
filter(function (a) {return a < 2}, [0, 1, 2, 3, 4]); // => [0, 1]
// Numbers divisible by 2
filter(function (a) {return (a % 2) == 0}, [0, 1, 2, 3, 4]); // => [0, 2, 4]
@walkermatt
Copy link
Author

To run either copy and paste into the devtools console of a browser or use .load map_reduce.js in a Node.js REPL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment