Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/**
* 人
*/
var person = function(spec){
var that = {};
var toString = function(){
return spec.name + " " + spec.age.toString();
};
that.toString = toString;
var getName = function(){
return spec.name;
};
that.getName = getName;
var getAge = function(){
return spec.age;
};
that.getAge = getAge;
return that;
};
/**
* グループ
*/
var group = function(spec){
var that = {};
var persons = [];
var add = function(ps){
persons[persons.length] = ps;
return that;
};
that.add = add;
var toString = function(){
return persons.join(",");
};
that.toString = toString;
var each = function(f){
var i;
for (i = 0; i < persons.length; i++) {
f(persons[i]);
}
};
that.each = each;
var map = function(f){
var result = [];
each(function(ps){
result[result.length] = f(ps);
});
return result;
};
that.map = map;
var filter = function(p){
var result = [];
each(function(ps){
if (p(ps)) {
result[result.length] = ps
}
});
return result;
};
that.filter = filter;
var fold = function(z, f){
var acc = z;
each(function(ps){
acc = f(acc, ps);
});
return acc;
};
that.fold = fold;
return that;
};
var g = group({}).add(person({
name: "Hanako",
age: 15
})).add(person({
name: "Jiro",
age: 15
})).add(person({
name: "Tarou",
age: 21
}));
g.each(function(ps){
console.log(ps.toString());
});
var g2 = g.map(function(ps){
return ps.getAge() * 2;
});
console.log(g2.toString());
var g3 = g.filter(function(ps){
return ps.getAge() < 20;
});
console.log(g3.toString());
var g4 = g.fold(0, function(acc, ps){
return acc + ps.getAge();
});
console.log(g4.toString());
var g4 = g.fold("", function(acc, ps){
return acc + ps.getName();
});
console.log(g4.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment