Сообщение от krutoy
|
bes,
Не взрывай мне мозг
|
лови fuel injection, possibly with slices of shit
ещё куча непокрытого, но твой случай покрывает
function type(el) {
var type = typeof el;
if ( type != "object" ) return type;
if ( el == null ) return "null";
if ( el.length || el.length >= 0 ) return "array";
return "object";
}
function len(obj) {
var n = 0;
for (var key in obj) {
n++;
}
return n;
}
function isEqual(obj1, obj2) {
if ( type(obj1) != "object" && type(obj2) != "object" ) return obj1 == obj2;
if ( len(obj1) != len(obj2) ) return false;
for (var key in obj1) {
if (obj1[key] === obj2[key]) {
continue;
}
return false;
}
return true;
}
function cloneObject(obj) {
var clone = {};
for (var key in obj) {
clone[key] = obj[key];
}
return clone;
}
function isSame(args1, args2) {
var len1 = args1.length;
var len2 = args2.length;
if ( len1 != len2 ) return false;
for (var i = 0; i < len1; i++) {
if ( isEqual(args1[i], args2[i]) ) continue;
return false;
}
return true;
}
function giblets(args) {
var giblet = [];
var length = args.length;
for ( var i = 0; i < length; i++ ) {
if ( type(args[i]) != "object" ) {
giblet.push(args[i]);
} else {
giblet.push( cloneObject(args[i]) );
}
}
return giblet;
}
function cacheFn(fn) {
var cache = [];
return function () {
var len = cache.length;
for (var i = 0; i < len; i++) {
if ( isSame(cache[i].args, giblets(arguments)) ) {
console.log("cache: " + cache[i].res + "\n\n");
return cache[i].res;
}
}
cache.push( {args: giblets(arguments), res: fn.apply(this, arguments)} );
console.log("call: " + cache[len].res + "\n\n")
return cache[len].res;
}
}
function f(obj) {
return obj.a + obj.b;
}
var cacheF = cacheFn(f);
o={b: 2}
var o1 = Object.create(o)
o1.a = 1
cacheF(o1);
cacheF(o1);
o.b=10
console.log("----");
cacheF(o1);
cacheF(o1);