2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-04-10 02:43:44 +00:00
|
|
|
// This module is browser compatible.
|
2023-11-05 12:49:00 +00:00
|
|
|
import { compareSimilarity } from "./compare_similarity.ts";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Sorts a string-array by similarity to a given string
|
|
|
|
*
|
2024-05-23 17:01:10 +00:00
|
|
|
* @example Usage
|
2023-11-05 12:49:00 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { wordSimilaritySort } from "@std/text/word-similarity-sort";
|
2023-11-05 12:49:00 +00:00
|
|
|
*
|
|
|
|
* const possibleWords = ["length", "size", "blah", "help"];
|
|
|
|
*
|
|
|
|
* // case-insensitive by default
|
|
|
|
* const suggestions = wordSimilaritySort("hep", possibleWords).join(", ");
|
|
|
|
*
|
|
|
|
* // force case sensitive
|
|
|
|
* wordSimilaritySort("hep", possibleWords, { caseSensitive: true });
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @param givenWord - The string to measure distance against
|
|
|
|
* @param possibleWords - The string-array that will be sorted
|
2024-05-23 17:01:10 +00:00
|
|
|
* @param options An options bag containing a `caseSensitive` flag indicating
|
|
|
|
* whether the distance should include case. Default is false.
|
2023-11-05 12:49:00 +00:00
|
|
|
* @returns {string[]} A sorted copy of possibleWords
|
|
|
|
*/
|
|
|
|
export function wordSimilaritySort(
|
|
|
|
givenWord: string,
|
|
|
|
possibleWords: string[],
|
|
|
|
options?: {
|
|
|
|
caseSensitive?: boolean;
|
|
|
|
},
|
|
|
|
): string[] {
|
|
|
|
const { caseSensitive } = { ...options };
|
|
|
|
|
|
|
|
// this distance metric could be swapped/improved in the future
|
|
|
|
return [...possibleWords].sort(
|
|
|
|
compareSimilarity(givenWord, { caseSensitive }),
|
|
|
|
);
|
|
|
|
}
|