Skip to content

Instantly share code, notes, and snippets.

@tylshe
Last active December 29, 2015 20:49
Show Gist options
  • Save tylshe/7726428 to your computer and use it in GitHub Desktop.
Save tylshe/7726428 to your computer and use it in GitHub Desktop.
test_1
var count = (function() {
var a = 0;
return function(){
var args = Array.prototype.slice.call(arguments[0]);
if(arguments.length !== 0){
for (var i = 0, lngth = args.length; i < lngth; i++) {
a += args[i];
}
}
return a;
}
}());
function counter(){
var f = arguments[0],
arr = Array.prototype.slice.call(arguments, 1);
return f.call(null, arr);
}
counter(count, 1);
counter(count, 2,3,4);
counter(count, 5,6,7,8);
console.log(counter(count)); // 8*9/2 = 36 profit =)
// №2
function sum(a,b){
return a+b;
}
function counter(){
var s = 0;
counter = function(){
if(arguments.length){
var f = arguments[0],
arr = Array.prototype.slice.call(arguments, 1);
s += f.apply(null, arr);
return s;
}
}
}
// closure init
counter();
console.log(counter(sum, 1,2));
console.log(counter(sum, 1,2));
// #3
function counter2(){
var f = arguments[0],
arr = Array.prototype.slice.call(arguments, 1);
counter2.cache += f.apply(null, arr);
return counter2.cache;
}
counter2.cache = 0;
counter2(sum, 1,2)
counter2(sum, 1,2)
console.log(counter2(sum, 1,2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment