zamf zamf - 3 years ago 157
Javascript Question

Function that will execute function depending on value. Functional programming

I have two functions and they are executed depending of if statement. E.g.:

if(value) {
doA()
} else {
doB()
}


How to write function or object that will take the result and decide whether or not execute each function. I want to receive something like this:

exists(result).doA()
nothing(result).doB()


I want to learn some functional programming in JavaScrit so I woud appreciate any source from which I can learn FP in JavaScript.

Answer Source

You could write something like this, for example:

function exists(value) {
    return function (func) {
        if (value !== undefined) {
            return func(value);
        }
        return null;
    }
}

function nothing(value) {
    return function (func) {
        if (value === undefined) {
            return func();
        }
        return null;
    }
}

function doA(value) {
    console.log('doing A', value);
}

function doB() {
    console.log('doing B');
}

const foo = 'fool';
const bar = undefined;

exists(foo)(doA);
nothing(bar)(doB);

The exists function gets a value and returns another function. The function that is returned gets yet another function as argument, which is executed if the value passed is defined.

I've used “old school” anonymous functions in the example above to make it easier to understand. With ES6 arrow functions, you can write the exists and nothing functions more consisely, like this:

function exists(value) {
    return func => value !== undefined ? func(value) : null;
}

function nothing(value) {
    return func => value === undefined ? func(value) : null;
}

The “functional programming fun” really starts when you realize you can refactor these two functions by putting the common code in another function, that is then used to create the two functions, like this:

function executeWithCondition(predicate) {
    return value => func => predicate(value) ? func(value) : null;
}

const exists = executeWithCondition(value => value !== undefined);
const nothing = executeWithCondition(value => value === undefined);

This technique is called currying.

Usage of these functions is still the same:

exists(foo)(doA);
nothing(bar)(doB);

Here's the complete runnable code example:

function executeWithCondition(predicate) {
    return value => func => predicate(value) ? func(value) : null;
}

const exists = executeWithCondition(value => value !== undefined);
const nothing = executeWithCondition(value => value === undefined);

function doA(value) {
    console.log('doing A', value);
}

function doB() {
    console.log('doing B');
}

const foo = 'fool';
const bar = undefined;

exists(foo)(doA);
nothing(bar)(doB);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download