Instantly share code, notes, and snippets.

Embed
What would you like to do?
const nullableDinero = ({ amount, ...rest }) => {
if (amount === null) {
return nullDinero;
}
let realDinero = Dinero({ amount, ...rest });
let wrapper = Object.create(realDinero); // delegate to realDinero by default
for (let method of ['add', 'subtract']) { // extend specific methods
wrapper[method] = other => other === nullDinero
? nullDinero
: realDinero[method].call(wrapper, other);
}
return wrapper;
};
const nullableDinero = ({ amount, ...rest }) => {
if (amount === null) {
return nullDinero;
}
let realDinero = Dinero({ amount, ...rest });
let wrappedMethods = ['add', 'subtract'];
let passthroughProperties = Object.getOwnPropertyNames(realDinero)
.filter(name => !wrappedMethods.includes(name));
let proxy = Object.create(
Object.getPrototypeOf(realDinero),
passthroughProperties.map(name => Object.getOwnPropertyDescriptor(name))
);
for (let method of wrappedMethods) {
proxy[method] = other => other === nullDinero
? nullDinero
: realDinero[method].call(proxy, other);
}
return proxy;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment