JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 131
  • Score
    100M100P100Q80258F
  • License ISC

Like Array.prototype.find, but for finding the closest match.

Package Exports

  • find-closest

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (find-closest) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

About

This module provides functions equivalent to Array.prototype.find and Array.prototype.indexOf, but for finding the closest value where an exact match may not exist.

Installation

npm install find-closest

API

findClosest(array, valueToFind)

import findClosest from 'find-closest';

findClosest([0, 10, 20], 12);
// returns 10

findClosest(array, valueToFind, [valueGetter])

import findClosest from 'find-closest';

const people = [
    {name: 'Bob', age: 20},
    {name: 'Laura', age: 16}
];
const getAge = ({age}) => age;

findClosest(people, 17, getAge);
// returns the object for Laura

createFindClosest(getDistance)

findClosest works for numbers. However, you may make other comparisons by creating a custom function with createFindClosest.

Pass a function to createFindClosest which calculates the distance between a value from the array and the expected value. The function should return a number, with a minimum value of 0. The better the match, the lower the number should be.

Basic example

import {createFindClosest} from 'find-closest';

const getDistance = (name, lengthToFind) =>
    Math.abs(name.length - lengthToFind)

const findClosestLength = createFindClosest(getDistance);

findClosestLength(['Bob', 'Laura', 'Timothy'], 10);
// returns 'Timothy'

Plugging in third party modules

It's simple to use a third-party module to calculate what "close" means. This example uses the "fast-levenshtein" module (installed via npm) to calculate the similarity between strings.

import {createFindClosest} from 'find-closest';
import levenshtein from 'fast-levenshtein';

const findClosestWord = createFindClosest(levenshtein.get);

findClosestWord(['Bob', 'Jo', 'Tim'], 'Rob');
// returns 'Bob'

findClosestIndex(array, valueToFind, [valueGetter])

Like findClosest, except it returns the index instead of the value from the array.

createFindClosestIndex(getDistance)

Like createFindClosest, except the created function returns the index instead of the value from the array.