Last active
November 7, 2015 01:50
-
-
Save jalehman/2583d3a5a1202d12bf55 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function each(array, f) { | |
for(var i = 0; i < array.length; i++) { | |
f(array[i]); | |
} | |
} | |
function map(array, f) { | |
var acc = []; | |
each(array, function(x) { | |
acc.push(f(x)); | |
}); | |
return acc; | |
} | |
function filter(array, p) { | |
var acc = []; | |
each(array, function(x) { | |
if (p(x)) { | |
acc.push(x); | |
} | |
}); | |
return acc; | |
}; | |
function odd(x) { | |
return x % 2 === 1; | |
} | |
filter([0,1,2,3,4,5], odd); | |
function compose(f, g) { | |
return function(x) { | |
return f(g(x)); | |
}; | |
} | |
function f(x) { return x + 1; } | |
function g(x) { return x * 2; } | |
var fOfG = compose(f, g); | |
var toastTypes = { | |
white: {time: 30}, | |
wheat: {timed: 60} | |
}; | |
var Toaster = function() { | |
var handle; | |
return { | |
toast: function (time, toast) { | |
handle = setTimeout(function () { | |
console.log ("Your toast is ready"); | |
handle = undefined; | |
}, time); | |
console.log("Toasting."); | |
}, | |
cancel: function () { | |
if (handle) { | |
console.log("Here's your partially toasted toast."); | |
clearTimeout (handle); | |
handle = undefined; | |
} else { | |
console.log ("You're not toasting anything!"); | |
} | |
} | |
}; | |
}; | |
function reduce(array, f, acc) { | |
var temp = acc; | |
for (var i = 0; i < array.length; i++) { | |
temp = f(temp, array[i]); | |
} | |
return temp; | |
} | |
function mapWithReduce(array, f) { | |
return reduce(array, function(acc, next) { | |
acc.push(f(next)); | |
return acc; | |
}, []); | |
} | |
// A "predicate" is a function that returns true or false. | |
function max(array, predicate) { | |
return reduce(array, function(next, acc) { | |
return predicate(acc, next) ? next : acc; | |
}, array[0]); | |
} | |
var people = [ | |
{first: "", last: "Lehman"}, {first: "David", last: "Tran"} | |
]; | |
max(people, function(previous, next) { | |
return (previous.first.length + previous.last.length) < (next.first.length + next.last.length); | |
}); | |
function longestWord(sentence) { | |
return max(sentence.split(" "), function(prev, next) { | |
return next.length > prev.length; | |
}); | |
} | |
longestWord("the quick brown fox jumped over the lazy dog"); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment