Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.
How to use
Install via yarn add locutus and import:
import { levenshtein } from 'locutus/php/strings/levenshtein'.
Or with CommonJS: const { levenshtein } = require('locutus/php/strings/levenshtein')
Use a bundler that supports tree-shaking so you only ship the functions you actually use.
Vite,
webpack,
Rollup, and
Parcel
all handle this. For server-side use this is less of a concern.
Examples
These examples are extracted from test cases that automatically verify our functions against their native counterparts.
#
code
expected result
1
levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld')
3
2
levenshtein("carrrot", "carrots")
2
3
levenshtein("carrrot", "carrots", 2, 3, 4)
6
Here's what our current TypeScript equivalent to PHP's levenshtein looks like.
exportfunctionlevenshtein(s1: string, s2: string, costIns?: number, costRep?: number, costDel?: number): number { // discuss at: https://locutus.io/php/levenshtein/ // parity verified: PHP 8.3 // original by: Carlos R. L. Rodrigues (https://www.jsfromhell.com) // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman) // revised by: Andrea Giammarchi (https://webreflection.blogspot.com) // reimplemented by: Brett Zamir (https://brett-zamir.me) // reimplemented by: Alexander M Beedie // reimplemented by: Rafał Kukawski (https://blog.kukawski.pl) // example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld') // returns 1: 3 // example 2: levenshtein("carrrot", "carrots") // returns 2: 2 // example 3: levenshtein("carrrot", "carrots", 2, 3, 4) // returns 3: 6
// var LEVENSHTEIN_MAX_LENGTH = 255 // PHP limits the function to max 255 character-long strings
if (l1 === 0) { return l2 * costIns } if (l2 === 0) { return l1 * costDel }
// Enable the 3 lines below to set the same limits on string length as PHP does // if (l1 > LEVENSHTEIN_MAX_LENGTH || l2 > LEVENSHTEIN_MAX_LENGTH) { // return -1; // }
if (l1 === 0) { return l2 * costIns } if (l2 === 0) { return l1 * costDel }
// Enable the 3 lines below to set the same limits on string length as PHP does // if (l1 > LEVENSHTEIN_MAX_LENGTH || l2 > LEVENSHTEIN_MAX_LENGTH) { // return -1; // }
Locutus is a community effort following
The McDonald's Theory:
we ship first iterations, hoping others will improve them.
If you see something that could be better, we'd love your contribution.