Javascript(ECMAScript) Functional JavascriptFunctional AspectsUntested lift from google-goopy. Feel free to fix and add more working examples.
var parts = partition((function (x) {return ((x % 2) == 0);}),
homogenousList);
var evens = parts[0];
var odds = parts[1];
// window.alert("evens = " + evens + " odds = " + odds);
var res = map((function (x) {return "stringified: " + x;}),
homogenousList);
window.alert(res);
iter(window.alert, homogenousList);
iter(window.alert, heterogenousMap);
window.alert(filter((function(x){return ((x%2)==1);}), homogenousList));
functional.js
function some(f, l) {
for (var x in l) {
if (f(l[x])) return true;
}
return false;
}
function every(f, l) {
for (var x in l) {
if (!f(l[x])) return false;
}
return true;
}
function find(p, l, start) {
var z = l.length;
var s;
if (arguments < 3) s = 0;
else s = start;
for (var i = s; i<z; ++i) {
if (p(l[i])) return i;
}
return -1;
}
/* Single list map functions that don't work with Javascript objects make the
* baby jesus cry!
* Question: Does Javascript's for/in loop give you the desired behavior of iterating
* over the elements of an array? */
function map(f, l) {
var res = [];
for (var i in l) {
res.push(f(l[i]));
}
return res;
}
/* Here's a fully general map that even works when f is a method of a specific object
* instance: */
function map(f, l0) {
var res = [], args = [];
for (var j = 0; j < l0.length; j++) {
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i][j]);
}
res.push(f.apply(this, args));
args = [];
}
return res;
}
function iter(f, l) {
for (var i in l) {
f(l[i]);
}
}
function fold_left(f, i, l) {
var a = i;
for (var i in l) {
a = f(a, l[i]);
}
return a;
}
function fold_right(f, i, l) {
var a = i;
var z = l.length-1;
for (var i=z; i >= 0; --i) {
a = f(l[i], a);
}
return a;
}
// filter(function p, array l)
//
// function p returns a boolean value. l contains
// the data to be filtered.
//
// the return value is an array containing all the elements
// in l for which p returns true.
function filter(p, l) {
var res = [];
for (var i in l) {
if (p(l[i])) res.push(l[i]);
}
return res;
}
// partition(function p, array l)
//
// function p returns a boolean value. l contains the
// data to be partitioned.
//
// The return value is an array containing two arrays: the first
// are those elements from l for which p returned true, and the second
// are the remainder.
function partition(p, l) {
var res1 = [];
var res2 = [];
for (var i in l) {
if (p(l[i])) res1.push(l[i]);
else res2.push(l[i]);
}
return [res1, res2];
}
// vim:set ts=4 sw=4 expandtab:
last updated 2 years ago # |
Internal Linksinfogami LinksWant more infogami? Check out a random site! Unofficial Python Tutorial Wiki PyTut Public Space |