Code Monkey home page Code Monkey logo

bktree's Introduction

bktree

BK-Tree for autocorrect

function zeros(n) {
  return Array(n).fill(0)
}

function matrix(row, col) {
  return Array(row).fill(
    () => zeros(col)
  ).map(fn => fn())
}

// Other edit distance includes hamming, jaccard etc.
function editDistance(s, t) {
  const [m, n] = [s.length, t.length]
  const dp = matrix(m + 1, n + 1)
  for (let i = 0; i <= m; i += 1) {
    dp[i][0] = i
  }
  for (let j = 0; j <= n; j += 1) {
    dp[0][j] = j
  }
  for (let i = 1; i <= m; i += 1) {
    for (let j = 1; j <= n; j += 1) {
      if (s[i - 1] !== t[j - 1]) {
        dp[i][j] = Math.min(
          1 + dp[i - 1][j], // Deletion.
          1 + dp[i][j - 1], // Insertion.
          1 + dp[i - 1][j - 1] // Replacement.
        )
      } else {
        dp[i][j] = dp[i - 1][j - 1]
      }
    }
  }
  return dp[m][n]
}

class Node {
  constructor(word = '') {
    this.word = word
    this.children = {}
  }
}

class BKTree {
  static TOL = 2

  constructor(dictionary = [], distanceFunction = editDistance) {
    this.distanceFunction = distanceFunction
    for (let word of dictionary) {
      this.add(word)
    }
  }

  add(str) {
    if (!this.root) {
      this.root = new Node(str)
      return
    }
    let curr = this.root
    let dist = this.distanceFunction(str, curr.word)
    while (curr.children[dist]) {
      curr = curr.children[dist]
      dist = this.distanceFunction(str, curr.word)
    }
    curr.children[dist] = new Node(str)
  }

  query(str) {
    const result = []
    const candidates = [this.root]

    while (candidates.length) {
      const node = candidates.pop()
      if (!node.word) {
        return result
      }
      const dist = this.distanceFunction(node.word, str)
      if (dist <= BKTree.TOL) result.push(node.word)

      let start = dist - BKTree.TOL
      if (start < 0) start = 1
      for (let i = start; i < dist + BKTree.TOL; i += 1) {
        if (node.children[i]) {
          candidates.push(node.children[i])
        }
      }
    }
    return result
  }
}

const dictionary = ['hell', 'help', 'shel', 'smell', 'fell', 'felt', 'oops', 'pop', 'oouch', 'halt']

// TODO: Load from generator instead of array.
const bkTree = new BKTree(dictionary)

console.log(bkTree.query('ops'))
console.log(bkTree.query('helt'))
console.log(bkTree.query('shelp'))

console.log(bkTree)

bktree's People

Contributors

alextanhongpin avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.