Created
November 12, 2018 21:59
-
-
Save alancnet/81188eb2ec53e628ecb4c400dd9e8503 to your computer and use it in GitHub Desktop.
Table WIP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const matchStart = (s1, s2) => { | |
const l = Math.max(s1.length, s2.length) | |
for (let i = 0; i < l; i++) { | |
if (s1[i] !== s2[i]) return i | |
} | |
return l | |
} | |
class Table { | |
constructor() { | |
this.data = {} | |
} | |
add(key, value) { | |
const add = (o, sub) => { | |
if (sub.length === 0) { | |
return o[sub] = value | |
} | |
const c = sub[0] | |
if (o.hasOwnProperty(c)) { | |
return add(o[c], sub.substr(1)) | |
} | |
// Find key matching first character | |
let keys = Object.keys(o) | |
for (let i = 0; i < keys.length; i++) { | |
const sub2 = keys[i] | |
let match = matchStart(sub, sub2) | |
if (match) { | |
if (match < sub2.length) { | |
const next = { | |
[sub2.substr(match)]: o[sub2], | |
} | |
o[sub2.substr(0, match)] = next | |
delete o[sub2] | |
return add(next, sub.substr(match)) | |
} else { | |
return add(o[sub2], sub.substr(match)) | |
} | |
} | |
} | |
o[sub] = { | |
'': value | |
} | |
return value | |
} | |
add(this.data, key) | |
} | |
} | |
sample = { | |
'foo': { | |
'bar': { | |
'': 'foobar' | |
}, | |
'baz': { | |
'': 'foobaz' | |
} | |
}, | |
'hel': { | |
'p': { | |
'': 'help' | |
}, | |
'o': { | |
'': 'hello' | |
} | |
} | |
} | |
module.exports= Table | |
Table = require('.'); t = new Table(); t.add('hello', 'hello'); t.add('help', 'help'); t.data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment