Last active
December 19, 2015 07:19
-
-
Save AKST/5917866 to your computer and use it in GitHub Desktop.
Fun with js functions. Just decided in implement my own version of map, filter, foldl, along with a few helper functions.
This file contains 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
Array.prototype.forEach = function (fun) { | |
for (var i = 0; i < this.length; i++) { | |
fun(this[i]); | |
} | |
}; | |
Array.prototype.foldl = function (acc, fun) { | |
this.forEach(function (elem) { | |
acc = fun(elem, acc); | |
}); | |
return acc; | |
} | |
Array.prototype.filter = function (fun) { | |
var result = []; | |
this.forEach(function (elem) { | |
if (fun(elem)) { | |
result.push(elem); | |
} | |
}); | |
return result; | |
} | |
Array.prototype.map = function (fun) { | |
var result = []; | |
this.forEach(function (elem, i) { | |
result.push(fun(elem)); | |
}); | |
return result; | |
} | |
// additional bool logic functions | |
function not (f) { | |
return function (e) { return !f(e); }; | |
} | |
function even (num) { return (num % 2) == 0; } | |
function odd (num) { return not(even)(num); } | |
function greaterThan(num1, num2) { | |
return num1 > num2; | |
} | |
function lesserThan(num1, num2) { | |
return num1 < num2; | |
} | |
function and (case1, case2) { | |
return function (e) { | |
return case1(e) && case2(e); | |
}; | |
} | |
function or (case1, case2) { | |
return function (e) { | |
return case1(e) || case2(e); | |
}; | |
} | |
// additional manlipulation functions | |
function square(num) { | |
return num * num; | |
} | |
function times(mulitplicant) { | |
return function (num) { | |
return num * mulitplicant; | |
}; | |
} | |
function mod (amount) { | |
return function (num) { | |
return num % amount; | |
}; | |
} | |
// generate list | |
function range(from, to, stepRange) { | |
var direction = from < to ? 1 : -1; | |
var result = []; | |
var step = ( stepRange !== undefined ? stepRange : 1) * direction; | |
var condition = direction < 0 ? greaterThan : lesserThan; | |
if (step !== 0) { | |
for (var i = from; condition(i, to + direction); i += step) { | |
result.push(i); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment