I have two functions and they are executed depending of if statement. E.g.:
if(value) {
doA()
} else {
doB()
}
exists(result).doA()
nothing(result).doB()
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);