JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 129
  • Score
    100M100P100Q80142F
  • 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)

Basic example

import {createFindClosest} from 'find-closest';

const findClosestLength = createFindClosest(({length}) => length);

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.