Memoized methods factory

Based on `d` descriptors factory.
It's first step to replace `method` option
This commit is contained in:
Mariusz Nowak
2013-10-23 18:18:39 +02:00
parent e1ed11b8d8
commit 0cc9969de0
3 changed files with 55 additions and 1 deletions

20
lib/d.js Normal file
View File

@@ -0,0 +1,20 @@
'use strict';
var forEach = require('es5-ext/object/for-each')
, callable = require('es5-ext/object/valid-callable')
, lazy = require('d/lazy')
, a = [], b = [];
module.exports = function (fn) {
var index = a.indexOf(callable(fn));
if (index !== -1) return b[index];
index = a.push(fn);
return (b[index - 1] = function (props) {
forEach(props, function (desc, name) {
var value = callable(desc.value);
desc.value = function (options) { return fn(value.bind(this), options); };
});
return lazy(props);
});
};

View File

@@ -34,7 +34,8 @@
"node": ">=0.4"
},
"dependencies": {
"es5-ext": "git://github.com/medikoo/es5-ext",
"d": "git://github.com/medikoo/d.git",
"es5-ext": "git://github.com/medikoo/es5-ext.git",
"event-emitter": "~0.2.2",
"next-tick": "0.1.x"
},

33
test/d.js Normal file
View File

@@ -0,0 +1,33 @@
'use strict';
var d = require('d')
, memoize = require('../lib/regular');
module.exports = function (t, a) {
var value = [], obj = {};
t = t(memoize);
Object.defineProperties(obj, t({
someFn: d(function (x, y) { a(this, obj); return x + y; },
{ refCounter: true,
dispose: function (val) { value.push(val); } })
}));
obj = Object.create(obj);
obj.someFn(3, 7);
obj.someFn(5, 8);
obj.someFn(12, 4);
a.deep(value, [], "Pre");
obj.someFn(5, 8);
obj.someFn.clearRef(5, 8);
a.deep(value, [], "Pre");
obj.someFn.clearRef(5, 8);
a.deep(value, [13], "#1");
value = [];
obj.someFn.clearRef(12, 4);
a.deep(value, [16], "#2");
value = [];
obj.someFn(77, 11);
obj.someFn.clearAll();
a.deep(value, [10, 88], "Clear all");
};