Skip to content

Instantly share code, notes, and snippets.

@carbide-public
Created April 4, 2017 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carbide-public/5a632917a5125d4d7be3345aef9d2a86 to your computer and use it in GitHub Desktop.
Save carbide-public/5a632917a5125d4d7be3345aef9d2a86 to your computer and use it in GitHub Desktop.
untitled
function forward(receiver, metaobject, ...methods) {
methods.forEach(function(methodName) {
receiver[methodName] = (...args) => metaobject[methodName](...args);
});
return receiver;
}
function delegate(receiver, metaobject, ...methods) {
methods.forEach(function(methodName) {
receiver[methodName] = (...args) =>
metaobject[methodName].apply(receiver, args);
});
return receiver;
}
const portfolio = (function() {
const investments = Symbol();
return {
[investments]: [],
addInvestment(investment) {
this[investments].push(investment);
},
netWorth() {
return this[investments].reduce(
function(acc, investment) {
return acc + investment.value;
},
0,
);
},
};
})();
const investor = forward({}, portfolio, 'addInvestment', 'netWorth');
investor.addInvestment({ type: 'art', value: 10 });
investor.addInvestment({ type: 'art', value: 20 });
investor.netWorth();
const banker = forward({}, portfolio, 'addInvestment', 'netWorth');
banker.addInvestment({ type: 'stocks', value: 100 });
banker.addInvestment({ type: 'stocks', value: 200 });
banker.netWorth();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment