trgm-js
v0.0.4
Published
Set of utilities for trigram comparison for JavaScript and TypeScript projects.
Maintainers
Readme
trgm-js
Provides utilities for working with trigrams in JavaScript and TypeScript. Comes with a firs-class TypeScript support and a simple API for comparing, sorting and searching strings based on their trigram similarity. Inspired by the pg_trgm PostgreSQL extension.
Installation
npm install trgm-jsUsage
You can use this package to compare and sort texts based on their trigram similarity.
Comparing strings
To compare two strings based on their trigram similarity, use the similarity function:
import { similarity } from "trgm-js";
const sim = similarity("dog", "dawg");
console.log(sim); // 0.125By default, trgm-js caps decimals places at 7. You can override this setting by passing a third argument to the similarity function:
import { similarity } from "trgm-js";
// Cap decimal places at 10
const sim = similarity("this is a longer text", "this is a longer string", 10);
console.log(sim); // 0.5714285714The result will always be stripped of trailing zeros, this setting only affects the cases in which the result has more decimal places than the specified cap.
Sorting
You can sort an array based on a similarity with a search term using the toSorted method.
import { toSorted } from "trgm-js";
const items = ["cat", "dawg", "dog", "pog"];
const sortedItems = toSorted(items, "dog");
console.log(sortedItems); // ['dog', 'dawg', 'pog', 'cat']toSorted creates a copy of the argument array and doesn't modify it. The default sort order is descending – the most similar words (i. e. those with the highest similarity scores) will appear first, less similar words later – but ordering can be changed to ascending by passing a third argument into the method.
import { toSorted } from "trgm-js";
const items = ["dog", "dawg"];
const sortedItems = toSorted(items, "dog", "asc");
console.log(sortedItems); // ["dawg", "dog"]Determining similarity
The areSimilar method uses the similarity treshold to determine whether two texts are similar enough. This treshold is a value of 0.3 by default, but you can change it by passing a third argument into the method.
import { areSimilar } from "trgm-js";
const result = areSimilar("Rosa", "Roska"); // Similarity of ~0.4
console.log(result); // true
const result2 = areSimilar("Rosa", "Roseberry"); // Similarity of ~0.2
console.log(result2); //false