0.0.2 • Published 6 years ago

@mck-p/trie v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

trie

Fast word and phrase search

Usage

// Require/import package
const createTrie = require('@mck-p/trie')

// Create Trie instance
const trie = createTrie()

// Add a word to the trie structure
trie.add('word')

// #search only returns true
// if the string is found AND
// it is found at a `isTail` node
trie.search('word') // true
trie.search('wor') // false

// #searchBy is a HoF that
// lets us search by a given
// function

// `If we have gotten to the end of the word,
// lets still return true, even if it isn't a
// full word`
const partialOk = node => node
// Create a function that lets us search the trie
// by whatever equality function we give it.
// We can also return the node itself, as we
// are above.
const searchTrie = trie.searchBy(partialOk)

Boolean(searchTrie('word')) // true 
Boolean(searchTrie('wor')) // true

// We can get access to the keys
// for someone else to do things with
trie.getKeys()
/*
  { w:
    { keys:
      { o:
        { keys:
          { r:
            { keys:
              { d:
                { keys: {}, isTail: true}
              }
            }
          }
        }
      }
    }
  }
*/

// We can load a list of words
// instead of calling `add` for 
// each one
trie.loadIndexes(['another', 'one'])

trie.getKeys()
/*
  {
    w: {...},
    a: {...},
    o: {...}
  }
*/

Options

const trie = createTrie({
  /*
    A function that given a string will
    return a list of keys to walk.

    Default:

        str => str.toLowerCase().split('')
  */
  getKeysFrom: str => [str],
  /*
    A function that given nothing will
    return a BasicNode interface, something
    with { keys }

    Default:

      () => ({ keys: {}, isHead: false, isTail: false })
  */
  createNode: () => BasicNode,
  /*
    A starting keys states

    Default:
    
      {}
  */
  keys: {}
})

Examples

You can find examples inside of the examples dir of how to interact with the trie structure for saving/reading cached keys, along with a JSON object of almost all English words.