Skip to content

Instantly share code, notes, and snippets.

@kesava
Created February 13, 2022 01:03
Show Gist options
  • Save kesava/a22d66eefe520adda469c531cb68d183 to your computer and use it in GitHub Desktop.
Save kesava/a22d66eefe520adda469c531cb68d183 to your computer and use it in GitHub Desktop.
const dict = ['computer', 'commuter', 'computation', 'computing', 'compute', 'computers'];
const letterDeletion = (word, index) => {
if (index === 0) return false;
let newWord = `${word.slice(0, index - 1)}${word.slice(index)}`;
if (dict.find(w => w === newWord)) {
return newWord;
} else {
return letterDeletion(word, index - 1);
}
}
const letterTransposition = (word, index) => {
if (index === 0) return false;
let newWord = `${word.slice(0, index - 2)}${word[index-1]}${word[index-2]}${word.slice(index)}`;
// console.log({ newWord })
if (dict.find(w => w === newWord)) {
return newWord;
} else {
return letterTransposition(word, index - 1);
}
}
const letterDuplication = (word, index) => {
if (index === 0) return false;
let newWord = `${word.slice(0, index - 1)}${word[index-1]}${word[index-1]}${word.slice(index)}`;
// console.log({ newWord });
if (dict.find(w => w === newWord)) {
return newWord;
} else {
return letterDuplication(word, index - 1);
}
}
const letters = 'abcdefghijklmnopqrstuvwxyz';
const letterInsertion = (word, index) => {
if (index === 0) return false;
for(let i = 0; i < 26; i++) {
let newWord = `${word.slice(0, index - 1)}${word[index-1]}${letters[i]}${word.slice(index)}`;
// console.log({ newWord });
if (dict.find(w => w === newWord)) return newWord;
}
return letterInsertion(word, index - 1);
}
function spellCheck(word) {
const wordLength = word.length;
let result = letterDeletion(word, wordLength);
if (result) return result;
result = letterTransposition(word, wordLength - 1);
if (result) return result;
result = letterDuplication(word, wordLength - 1);
if (result) return result;
result = letterInsertion(word, wordLength);
if (result) return result;
return word;
}
spellCheck('comuters')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment