Skip to content

Instantly share code, notes, and snippets.

@NickTomlin
Last active August 29, 2015 14:13
Show Gist options
  • Save NickTomlin/2153e0fdf7511c559c21 to your computer and use it in GitHub Desktop.
Save NickTomlin/2153e0fdf7511c559c21 to your computer and use it in GitHub Desktop.
nodeschool functional-programming
function firstAttempt () {
return Array.prototype.reduce.call(arguments, function (accum, arg) {
return Object.prototype.hasOwnProperty.call(arg, 'quack') ?
accum + 1
: accum;
}, 0);
};
// a tweak on their solution that avoids calling slice
function secondAttempt () {
return Array.prototype.filter.call(arguments, function (obj) {
return Object.prototype.hasOwnProperty.call(obj, 'quack')
}).length;
};
// their solution:
function duckCount() {
return Array.prototype.slice.call(arguments).filter(function(obj) {
return Object.prototype.hasOwnProperty.call(obj, 'quack')
}).length
}
module.exports = secondAttempt;
var reduce = module.exports = function reduce (arr, fn, init) {
function recurse(result, index) {
if (index === arr.length) return result;
var item = arr[index];
var rest = arr.slice(index);
var next = index + 1;
return recurse(fn(result, item, index, arr), next);
}
return recurse(init, 0);
}
module.exports = function spy (obj, methodName) {
var details = {
count: 0
};
var orig = obj[methodName];
obj[methodName] = function () {
details.count = details.count + 1;
return orig.apply(obj, arguments);
}
return details;
};
// this was pretty hard; I had to do some research and ended up with a more verbose solution
// mostly stolen from http://raganwald.com/2013/03/28/trampolines-in-javascript.html
// I think the key here is just understanding the idea of stack frames, and how this sidesteps that limitation
// by not creating this N long chain of recursion
// could I implmeent tail recursion optimization in anything after this? Probably not.
function repeat(operation, num) {
if (num <= 0) { return; }
operation()
--num;
return function () {
return repeat(operation, num);
};
}
function trampoline(fn) {
var rest = Array.prototype.slice.call(arguments, 1);
var result = fn.apply(fn, rest);
while(result instanceof Function) {
result = result();
}
return result;
}
module.exports = function(operation, num) {
return trampoline(repeat, operation, num)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment