JSFiddle - React, Tailwind, and code Playground
HTML
<div class="output"></div>
JavaScript
ClosestValue = function(values) {
this.values = values;
}
ClosestValue.prototype.getClosestSmaller = function(value) {
this.value = value;
return this.values.reduce($.proxy(this.reduceSmaller, this), Number.NEGATIVE_INFINITY);
}
ClosestValue.prototype.getClosestBigger = function(value) {
this.value = value;
return this.values.reduce($.proxy(this.reduceBigger, this), Number.POSITIVE_INFINITY);
}
ClosestValue.prototype.reduceSmaller = function(currentClosest, currentValue) {
return (currentClosest < currentValue) && (currentValue < this.value) ? currentValue : currentClosest;
}
ClosestValue.prototype.reduceBigger = function(currentClosest, currentValue) {
return (currentClosest > currentValue) && (currentValue > this.value) ? currentValue : currentClosest;
}
var instance = new ClosestValue([0, 5, 30, 7, 11, 9, 22, 18, 27]);
$('.output').append($('<p/>').html("The array of values is: " + instance.values));
$('.output').append($('<p/>').html("Closest smaller number to 10 is: " + instance.getClosestSmaller(10)));
$('.output').append($('<p/>').html("Closest bigger number to 10 is: " + instance.getClosestBigger(10)));
$('.output').append($('<p/>').html("Closest smaller number to 50 is: " + instance.getClosestSmaller(50)));
$('.output').append($('<p/>').html("Closest bigger number to 50 is: " + instance.getClosestBigger(50)));
$('.output').append($('<p/>').html("Closest smaller number to -1 is: " + instance.getClosestSmaller(-1)));
$('.output').append($('<p/>').html("Closest bigger number to -1 is: " + instance.getClosestBigger(-1)));