Is it possible to prevent a function execution if an object is returned?
function number(a) {
console.log(a)
return {
add: b => console.log(a + b)
}
}
number(6).add(4)
This will print 6 and then 10. The behaviour I am looking for is to only print 10 when .add() is called but print 6 if .add() is not called. .add() should somehow stop number() execution after It has happened (what?). I have never seen such a thing in javascript, so I am almost sure It's not possible but maybe I am missing something?
Edit
As requested, I will include a more realistic example. Note: this is only a research for nice syntax, I know how to achieve the functionality with different syntax.
function update(obj, props) {
for (const p in props) {
obj[p] = props[p]
}
return {
if(condition) {
for (const p in condition) {
if (obj[p] === condition[p]) {
obj[p] = props[p]
}
}
}
}
}
const obj1 = {z: 0, h: 0}
const obj2 = {a: 0, b: 'hi'}
update(obj1, {z: 10, h: 10}) // Will update the object regardless.
update(obj2, {a: 100, b: 'hello'}).if({a: 'x', b: 'y'}) // This would not update the object, because the condition is not met. (But it does)
console.log(obj1)
console.log(obj2)