Search code examples
javascriptalgorithmbotsdiscord.jsprediction

Predict JavaScript string from incorect input


I'm currently programming a Discord bot, and was wondering if it is possible to predict the wanted command if the input was incorrect.

For example, I have this list of words : ['help','meme','ping'], and if the user inputs "hepl", would it somehow be possible to "guess" they meant to type help ?


Solution

  • One option would be to find a command whose levenshtein distance from the input is 2 or less:

    // https://gist.github.com/andrei-m/982927
    const getEditDistance=function(t,n){if(0==t.length)return n.length;if(0==n.length)return t.length;var e,h,r=[];for(e=0;e<=n.length;e++)r[e]=[e];for(h=0;h<=t.length;h++)r[0][h]=h;for(e=1;e<=n.length;e++)for(h=1;h<=t.length;h++)n.charAt(e-1)==t.charAt(h-1)?r[e][h]=r[e-1][h-1]:r[e][h]=Math.min(r[e-1][h-1]+1,Math.min(r[e][h-1]+1,r[e-1][h]+1));return r[n.length][t.length]};
    
    const commands = ['help','meme','ping'];
    const getCommand = (input) => {
      if (commands.includes(input)) return input;
      return commands.find(command => getEditDistance(input, command) <= 2);
    };
    console.log(getCommand('hepl'));

    (2 is just a number, feel free to pick the tolerance you want - the higher it is, the more commands will be guessed at, but the more false positives there will be)