|
| 1 | +/** |
| 2 | + * Segment id distance of A to z is 57. Add 1 became 58. |
| 3 | + * If each char has 8 length at most, then there is a combination 58^8 = 128063081718016. |
| 4 | + * Then all combination is 58^9 = 7427658739644928. |
| 5 | + */ |
| 6 | +const STRING_ENCODING_LENGTH = 8; |
| 7 | +const STRING_SEGMENT = 58; |
| 8 | +const STRING_COMBINATION = STRING_SEGMENT ** STRING_ENCODING_LENGTH; |
| 9 | + |
| 10 | +export default class RedBlackNode { |
| 11 | + /** |
| 12 | + * Red-black tree node constructor. |
| 13 | + * Each node has key->value to facilitate table lookup. |
| 14 | + * @constructor |
| 15 | + * @param {(string|number)} key - key or index. |
| 16 | + * @param {object} value - value. |
| 17 | + * @param {boolean} color - parent's color. |
| 18 | + */ |
| 19 | + constructor(key = null, value = null, color = null, size = 1) { |
| 20 | + this.left = null; |
| 21 | + this.right = null; |
| 22 | + if (typeof key === 'string') { |
| 23 | + if (key.length > STRING_ENCODING_LENGTH) { |
| 24 | + throw new Error('String type key exceed STRING_ENCODING_LENGTH'); |
| 25 | + } |
| 26 | + } |
| 27 | + this.key = key; |
| 28 | + this.value = value; |
| 29 | + this.color = color; // Color of parent link |
| 30 | + this.size = size; // Size of subtree |
| 31 | + } |
| 32 | + |
| 33 | + decodeStrKey(key) { |
| 34 | + if (typeof key !== 'string') { |
| 35 | + throw new Error('Input should be string'); |
| 36 | + } |
| 37 | + |
| 38 | + let k = 0; |
| 39 | + if (key.length > 1) { |
| 40 | + k = [...key.slice(1)] |
| 41 | + .map(char => char.charCodeAt(0) - 64) |
| 42 | + .reduce((current, previous) => current + previous); |
| 43 | + } |
| 44 | + k += (key.charCodeAt(0) - 64) * STRING_COMBINATION; |
| 45 | + |
| 46 | + return k; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Compare two node based on their keys |
| 51 | + * @param {object} node - node to compare. |
| 52 | + * @returns {Number} comparation result. |
| 53 | + */ |
| 54 | + compareTo(node) { |
| 55 | + if (typeof this.key === 'number' && typeof node.key === 'number') { |
| 56 | + if (this.key > node.key) return 1; |
| 57 | + if (this.key < node.key) return -1; |
| 58 | + return 0; |
| 59 | + } |
| 60 | + if (typeof this.key === 'string' && typeof node.key === 'string') { |
| 61 | + // Compare based on sum of char codes |
| 62 | + const key1 = this.decodeStrKey(this.key); |
| 63 | + const key2 = this.decodeStrKey(node.key); |
| 64 | + |
| 65 | + if (key1 > key2) return 1; |
| 66 | + if (key1 < key2) return -1; |
| 67 | + return 0; |
| 68 | + } |
| 69 | + const t1 = typeof this.key; |
| 70 | + const t2 = typeof node.key; |
| 71 | + throw new Error(`Not consistent comparation type: ${t1} versus ${t2}`); |
| 72 | + } |
| 73 | +} |
0 commit comments