eulercode
eulercode

Reputation: 1157

wrap if else statement as function

Suppose i have following if else statement code.

if (checkValue(3)) {
    doFunction();
} else {
    alert('Fail');
}

function checkValue(value) {
    return value;
}

And i want to convert it to following to return same result.

checkValue(3, doFunction());

How can it be done?

Note: I do not want to repeat if else because this would be use multiple times in my code. Neither do i want to use ternary operator

Upvotes: 0

Views: 346

Answers (2)

Rafael
Rafael

Reputation: 7746

Try to keep your functions generic. Your function doesn't do anything important, as pointed out; here's a kick-start to better code:

function eq_functor(a, b) {
    return function () {
        return (a == b);
    };
}

function if_call(pred_fn, true_cb, fail_cb) {
    return pred_fn() ? true_cb() : fail_cb();
}

function bind_args(fn, args, _this = this) {
    return fn.bind(_this, ...args);
}

var x = 3;

if_call(
    eq_functor(x, 3),
    bind_args(console.log, ['success']),
    bind_args(console.log, ['fail'])
);

Side note: If I ever saw this code in production, I would raise hell to the developer who made it, simply because its more cryptic than it's helpful. Imagine if the developer tried to cleverly put this in a if, else if, else block...

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

Use a callback like this

function checkValue(value, cb) {
    if (value) {
        cb(value);
    } else {
        alert('Fail')
    }
}

checkValue(3, doFunction);

NOTE: don't pass doFunction(), you want to pass a function, not the result of calling a function

Upvotes: 4

Related Questions