项目作者: wdalmut

项目描述 :
An example of radix tree (not space optimized)
高级语言: JavaScript
项目地址: git://github.com/wdalmut/radix-tree.git
创建时间: 2018-09-08T07:27:26Z
项目社区:https://github.com/wdalmut/radix-tree

开源协议:

下载


Radix Tree kata

A simple (not space optimized) radix tree example

  1. const { add, get, del, keys } = require('./src');

Add elements

  1. let root = {};
  2. root = add('test', 'value', root);

Get existing elements

  1. get('test', root);
  2. 'value'

Remove existing elements

  1. root = del('test', root);

Get all keys of a prefix (autocomplete)

  1. keys('te', root)
  2. console.log(suggests)
  3. ['test', 'testa', 'tester']

Create extra features

Prepare a set of functional helpers

  1. const curry2 = fn => a => b => fn(a,b)
  2. const map = (fn, data) => data.map(fn)
  3. const nthArg = (pos) => (...args) => args[pos]
  4. const compose = (g, f) => (...args) => g(f.apply(null, args))
  5. const flip = (fn) => (...args) => fn.apply(fn, args.slice().reverse())
  6. const assoc = (key, value, data) => Object.assign({}, {[key]:value}, data)
  7. const converge = (fn, paths) => (...args) => fn.apply(null, paths.map((fn) => fn.apply(null, args)))
  8. const zipObj = (keys, values) => keys.reduce((memo, item, pos) => assoc(item, values[pos], memo), {})

Get all existing keys

  1. const allKeys = curry2(keys)('');
  2. allKeys(root);
  3. ['test', 'testa']

Get all values for a given prefix

  1. const values = converge(map, [compose(curry2(flip(get)), nthArg(1)), keys])
  2. values('te', root)
  3. ['value', 'value2']

Get all elements of a given prefix

  1. const all = converge(zipObj, [keys, values])
  2. all('te', root)
  3. { testa: 'value2', test: 'value' }