Strings one edit away

Determines if two strings are one edit away

by Alex Myronov

JavaScript

const isOneEditAway = (str1, str2) => {
  const s1 = str1.length < str2.length ? str1 : str2
  const s2 = str1.length < str2.length ? str2 : str1

  let index1 = 0
  let index2 = 0
  let firstMismatch = false
  while (index1 < s1.length && index2 < s2.length) {
    if (s1[index1] !== s2[index2]) {
    	if (firstMismatch) return false
      
      firstMismatch = true
      if (s1.length === s2.length) {
      	index1++
      }
    } else {
    	index1++
    }
		index2++
  }
  
  return true
}

console.log(isOneEditAway('pale', 'ple'))  // true
console.log(isOneEditAway('pale', 'ple'))  // true
console.log(isOneEditAway('pale', 'bale')) // true
console.log(isOneEditAway('pale', 'bae'))  // false