Skip to content

Instantly share code, notes, and snippets.

@swannodette
Created December 13, 2012 20:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swannodette/4279767 to your computer and use it in GitHub Desktop.
Save swannodette/4279767 to your computer and use it in GitHub Desktop.
Code from HackerSchool afternoon session
var data = [0,1,2,3,4,5,6,7,8,9];
function test() {
var result = [];
for(var i = 0; i < data.length; i++) {
if(data[i] % 2 == 0) {
result.push(data[i]*2);
}
}
console.log(result);
var sum = 0;
for(var i = 0; i < result.length; i++) {
sum = sum + result[i];
}
console.log(sum);
}
function even(n) { return n % 2 == 0; };
function mul2(n) { return n * 2; };
function sum(a, b) { return a + b; };
// data.map(mul2).filter(even).reduce(sum)
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 not(f) {
return function() {
return !f.apply(null, arguments);
};
}
function sameFirstChar(s1, s2) {
return s1[0] == s2[0];
}
function object(x) {
var secret = "can't see me!";
return {
setX: function(y) { x = y; },
getX: function() { return x; }
};
}
var people = [{first: "Bob", last: "Smith"},
{first: "John", last: "Smith"},
{first: "Mary", last: "Joe"}];
function format_name(p) {
return p.last + ", " + p.first;
}
function last_name(p) {
return p.last;
}
function property(prop) {
return function(obj) {
return obj[prop];
};
}
/*
function lazyseq(h, f) {
return {
head: h,
tail: f
};
}
function ints(start) {
return lazyseq(start, function() {
return ints(start+1);
});
}
function map(f, seq) {
if(seq == null) return null;
return lazyseq(f(seq.head), function() {
return map(f, seq.tail());
});
}
function filter(test, seq) {
if(seq == null) return null;
if(test(seq.head)) {
return lazyseq(seq.head, function() {
return filter(test, seq.tail());
});
}
return filter(test, seq.tail());
}
function take(n, seq) {
if(seq == null) return null;
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 repeat(x) {
return lazyseq(x, function() {
return repeat(x);
});
}
function interleave(s1, s2) {
if(s1 == null) return null;
if(s2 == null) return null;
return lazyseq(s1.head, function() {
return lazyseq(s2.head, function() {
return interleave(s1.tail(), s2.tail());
});
});
}
*/
<html>
<head>
<script type="text/javascript" src="fun.js"></script>
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment