Nishant - 1 year ago 55

Javascript Question

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`

`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

`<`

`>`

`lt`

`gt`

`predicate`

`lt`

`gt`

`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 Source

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