Get closest
Compare your item to items in an array and get the closest one. It comes by default with number comparison tools but it can also be used with strings, or anything else that you want to compare.
Installation
npm install get-closest
How to use
Require get-closest:
var getCloset = require("get-closest");
Let's say that you have an array of items such as:
var items = [0, 10, 15, 20, 50];
And that you want to get the item that's the closest to the number 18, which would be 20 in our case:
getCloset.number(18, items);
If you want to find the closest to 17.5, as it's exactly between 15 and 20, closest
will return the last item in the array that matches, which is 20 in our case.
getCloset.closest(17.5, items);
getCloset.closest(35, items);
If you're interested in getting the closest item that is greater, you can use greaterNumber
:
tools.greaterNumber(1, items);
If there's an exact match, it's returned. The last exact match will be returned too, to be consistent .closest.
getCloset.greaterNumber(0, items);
Finally, you can get the closest item that is lower, using lowerNumber
:
getCloset.lowerNumber(9, items);
getCloset.lowerNumber(10, items);
But you can also compare custom types by giving a custom comparison function, like string comparison with the levensthein distance:
function compareLevenshteinDistance(compareTo, baseItem) {
return new Levenshtein(compareTo, baseItem).distance;
}
var days = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];
getCloset.custom("mercure", days, compareLevenshteinDistance);
LICENSE
MIT