Skip to content

Instantly share code, notes, and snippets.

@mistersourcerer
Forked from guilhermesilveira/gist:2378419
Created April 13, 2012 17:30
Show Gist options
  • Save mistersourcerer/2378603 to your computer and use it in GitHub Desktop.
Save mistersourcerer/2378603 to your computer and use it in GitHub Desktop.
abusing _ scala in javascript
Array.prototype.map = function(f) {
return this.fold([], function(current, el) {
return [f(current)].concat(el);
});
}
Number.prototype.sum = function(val) {
return this + val;
}
/*
Paulo Silveira @paulo_caelum
@sr_valeriano @guilhermecaelum
fold(array, op, init) { if(array.length == 0) return init;
return op(array[0], fold(array[...], op, init); }
*/
Array.prototype.fold = function(init, f) {
if (this.length == 0) {
return init;
}
return f(this[0], this.slice(1).fold(init, f));
}
console.log("::::")
a = ["1", "2", "3"];
r = a.map(function(a) {
return a.concat(":");
});
console.log(r);
console.log("::::")
a = [1, 2, 3];
r = a.fold(1, function(a, b) {
return a + b;
})
console.log(r);
Array.prototype.inject = Array.prototype.fold;
// any browser:
console.log("any browser:");
var fruits = ["banana", "orange", "lemon"];
var result = fruits.fold("*", function(i, v) {
return i.concat(v);
});
console.log(result);
var numbers = [1, 2, 3];
result = numbers.fold(10, function(i, v) {
return i + v;
});
console.log(result);
console.log("__________");
// only ffox:
console.log("just firefox:");
var _ = {};
_.__noSuchMethod__ = function(method, args) {
var hasLazyArgument = args[0] == _;
return (function(target){
if (hasLazyArgument) {
args = Array.prototype.slice.call(arguments);
target = args.shift();
}
if (target[method]) {
return target[method].apply(target, args);
} else {
console.log(target + "." + method + "()");
target[method]();
}
});
}
var fruits = ["banana", "orange", "lemon"];
var result = fruits.fold("***", _.concat(_));
console.log(result);
result = fruits.map(_.concat(":::"));
console.log(result);
result = fruits.inject("***", _.concat(_));
console.log(result);
<!DOCTYPE html>
<html>
<head><title>go</title></head>
<body>
<script src="_.js"></script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment