Home > Software design >  Javascript: prevent function execution if object is returned
Javascript: prevent function execution if object is returned

Time:11-14

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)

CodePudding user response:

Just don't console.log() from within either function. Return the values and do your console.log() outside.

console.log(
  number(6).add(4)
);

If you're going to design a chaining API like this, take care to not have weird side effects. Make each function do a single distinct thing.

CodePudding user response:

[It] should somehow stop […] execution after it has happened (what?).

This is not possible. Neither can the if method change the past, nor can the update method predict whether .if() will be called on its return value in the future. The best you could do afterwards is to undo what was done before, but that's quite ugly.

Instead, change your syntax from

update(obj2, {a: 100, b: 'hello'}).if({a: 'x', b: 'y'});

to something like

when({a: 'x', b: 'y'}).update(obj2, {a: 100, b: 'hello'})

or (if you only want to introduce one variable update) like

update.if({a: 'x', b: 'y'}).then(obj2, {a: 100, b: 'hello'})
  • Related