The wonders of emily.js: closest/closestGreater/closestLower
Emily.js has a great bunch of modules to allow you build scalable and fast applications, but it also has some hidden gems that happen to be very useful, solving common problems that we usually overlook and work around with an ad-hoc solution.
Today’s hidden gem is closest/closestGreater/closestLower from Tools.
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:
tools.closest(18, items); // 3, as items[3] === 20;
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.
tools.closest(17.5, items); // 3, as items[3] === 20 tools.closest(35, items); // 4, as items[4] === 50
If you're interested in getting the closest item that is greater, you can use closestGreater:
tools.closestGreater(1, items); // 1, as items[1] === 10
If there's an exact match, it's returned:
tools.closestGreater(0, items); // 0, as items[0] === 0 is an exact match.
Finally, you can get the closest item that is lower, using closestLower:
tools.closestLower(9, items); // 0, as items[0] === 0; tools.closestLower(10, items); // 1, as items[1] === 10;















