Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Created December 13, 2012 20:17
Show Gist options
  • Save zachallaun/4279430 to your computer and use it in GitHub Desktop.
Save zachallaun/4279430 to your computer and use it in GitHub Desktop.
var data = [0,1,2,3,4,5,6,7,8,9];
function test() {
var g = window;
g.result = [];
for(var i = 0; i < data.length; i++) {
if(data[i] % 2 === 0) {
g.result.push(data[i]*2);
}
}
g.sum = 0;
for(i = 0; i < result.length; i++) {
g.sum += result[i];
}
}
var animals = ["dog", "bird", "cat"];
function map(f, arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(f(arr[i]));
}
return result;
}
function filter(test, arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (test(arr[i])) {
result.push(arr[i]);
}
}
return result;
}
function reduce(f, init, arr) {
var acc = init;
for (var i = 0; i < arr.length; i++) {
acc = f(acc, arr[i]);
}
return acc;
}
function mul2(n) { return n * 2; }
function even(n) { return n % 2 === 0; }
function not(test) { return function(x) { return !test(x); }; }
function sum(a, b) { return a + b; }
// data.filter(even).map(mul2).reduce(sum);
// generic not that accepts many arguments
function negate(test) {
return function() {
return !test.apply(null, arguments);
};
}
// Lazy sequences
function lazyseq(h, f) {
return {
head: h,
tail: f
};
}
function ints(start) {
return lazyseq(start, function() { return ints(start+1); });
}
function take(n, seq) {
if (n === 0) return null;
return lazyseq(seq.head, function() {
return take(n - 1, seq.tail());
});
}
function into_array(seq) {
var result = [];
while(seq) {
result.push(seq.head);
seq = seq.tail();
}
return result;
}
function lmap(f, seq) {
if (seq === null) return null;
return lazyseq(f(seq.head), function() {
return lmap(f, seq.tail());
});
}
function lfilter(test, seq) {
if (seq === null) return null;
if (test(seq.head)) {
return lazyseq(seq.head, function() {
return lfilter(test, seq.tail());
});
} else {
return lfilter(test, seq.tail());
}
}
function repeat(x) {
return lazyseq(x, function() {
return repeat(x);
});
}
function interleave(seqa, seqb) {
if (seqa === null) return null;
if (seqb === null) return null;
return lazyseq(seqa.head, function() {
return interleave(seqb, seqa.tail());
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment