Nishant
Nishant

Reputation: 21914

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.

Upvotes: 2

Views: 104

Answers (2)

Mulan
Mulan

Reputation: 135207

@Nina's answer points you in the right direction but Math.max and Math.min are not predicates. And the answer is overly complicated.

I see no reason why the answer should be harder to follow than this

function calculateValue(delta, final, current) {
  return (delta > 0 ? Math.min : Math.max)(final, current);
}

calculateValue(-1, 5, 10); // 10
calculateValue(1, 5, 10);  // 5

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

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));

Upvotes: 1

Related Questions