Nishant Nishant - 6 months ago 21
Javascript Question

Avoiding repetition using higher order functions in JS?

How to write this snippet more functionality by avoiding repetitions of function creation like this in JavaScript? Just to give a context, I am trying find if the movement from current value to final value has already been achieved..

deltaValue
is positive if the movement is towards a higher value and negative if its towards a lower value.

if (deltaValue > 0) {
maxPossibleValue = function(current, final) {
return current > final ? final : current;

}
} else {
maxPossibleValue = function(current, final) {
return current < final ? final : current;
}
}


Assuming there existed
<
and
>
as functions,
lt
and
gt
in JavaScript, I could have just evaluated this with a single function where
predicate
is
lt
and
gt
dealing with higher order functions. However there are no such functions natively in JS, so is the above method the only way?

maxPossibleValue = function(predicate) {
return function(c, f) {
return predicate(c, f) ? c : f }
}


This can be thought as just templating the required predicate function and returning a new function. I have seen such patterns in Scheme.

Answer

You have already a mechanism for your requirement, Math.min and Math.max.

The code looks like this, but maxPossibleValue is missleading

var maxPossibleValue = function (predicate) {
        return function (c, f) {
            return predicate(c, f)
        }
    },
    comparer = maxPossibleValue(deltaValue > 0 ? Math.min : Math.max);

Working example:

var deltaValue = -1;
var maxPossibleValue = function (predicate) {
        return function (c, f) {
            return predicate(c, f)
        }
    },
    comparer = maxPossibleValue(deltaValue > 0 ? Math.min : Math.max);

document.write(comparer(2, 8));