Character Vault
Any Concept / Any System
Compendium
Your System Come To Life
Roll20 for Android
Streamlined for your Tablet
Roll20 for iPad
Streamlined for your Tablet

Personal tools

Script:levenshteinDistance

From Roll20 Wiki

Jump to: navigation, search
API ScriptAuthor: Brian
Version: 1.1
Last Modified: 2016-03-09
Code: levenshteinDistance
Dependencies: None
Conflicts: None

levenshteinDistance is a string comparison function. The metric was developed by Vladimir Levenshtein in 1965. The function tracks the difference between two strings based on single-character changes. In other words, the number of insertions, deletions, and substitutions required to change the first string into the second. This metric is useful for deciding what strings are "close" to being the same, such as finding a partial match against a player or character name.

The levenshteinDistance function is added to String.prototype, meaning it can be treated as a function of string objects.

Original JavaScript implementation from wikibooks.org.

Contents

Syntax

str.levenshteinDistance(otherStr)

Parameters

otherStr
The string to compare against str.

Return Value

levenshteinDistance returns an integer of the total number of insertions, deletions, and substitutions required to change str into otherStr.

Example

The distance between "kitten" and "sitting" is 3:

  1. kitten → sitten (substitute "s" for "k")
  2. sitten → sittin (substitute "i" for "e")
  3. sittin → sitting (insert "g")
on('chat:message', function(msg) {
    var params = msg.content.splitArgs(),
        command = params.shift().substring(1).toLowerCase(),
        characterName = params[0],
        potentialCharacters, foundCharacter;

    if (msg.type === 'api' && command === 'echocharacter') {
        potentialCharacters = filterObjs(function(obj) { return obj.get('type') === 'character' && obj.get('name').indexOf(who) >= 0; });
        foundCharacter = _.sortBy(potentialCharacters, function(chr) {
            return chr.get('name').toLowerCase().levenshteinDistance(who.toLowerCase());
        })[0];

        if (foundCharacter) {
            sendChat('System', characterName + ' interpreted as ' + foundCharacter.get('name'));
        } else {
            sendChat('System', 'Could not find character for ' + characterName);
        }
    }
});

Changelog

v1.1 (2016-03-09)

  • Update for one-click install


v1.0 (2015-01-08)

  • Release