我有一个工厂函数( objectFactory ),我想重用其他工厂(例如,可观察的工厂)。
*.inc(1)
的方法)?const pipe = (...fns) => x => fns.reduce( (prev, func) => func(prev), x);
const compose = (...fn) => obj => pipe(...fn)(obj);
const freeze = o => Object.freeze(o);
const observable = o => {
const observers = {};
const keys = () => Object.getOwnPropertySymbols(observers).map(k => observers[k]);
return {
...o,
subscribe(obj) {
const id = Symbol();
observers[id] = obj;
return { id: id, unsubscribe: this.unsubscribe.bind(this, id) };
},
unsubscribe(id) {
delete observers[id];
},
notify(value) {
keys().forEach(obj => obj.update(value));
}
};
};
const loggable = text => o => {
return {
...o,
log: (...args) => { console.log(text, ...args); }
};
};
// This is the factory
function objectFactory(value, name = 'my factory') {
var $value = value;
return compose(
observable,
loggable(name),
freeze)({
get: () => $value,
set: set
});
function set(val) {
$value = val;
this.log('log the set value', $value);
this.notify($value);
}
}