UNPKG

2.89 kBJavaScriptView Raw
1import { LinkList } from "../linklist/LinkList";
2import { BasicBinaryTree } from "../tree/basic-binary-tree/BasicBinaryTree";
3import { RedBlackTree } from "../tree/red-black-tree/RedBlackTree";
4import { hash, toString } from "../util";
5export class TreeMap {
6 constructor() {
7 this.size = 0;
8 this.tree = new RedBlackTree("key");
9 }
10 get Count() {
11 return this.size;
12 }
13 put(key, value) {
14 let link = this.get(key);
15 if (link) {
16 const node = link.findNode(item => item.key === key);
17 if (node) {
18 node.Value.value = value;
19 return this;
20 }
21 link.append({ key, value });
22 this.size++;
23 return this;
24 }
25 this.size++;
26 const hashKey = this.getHashKey(key);
27 const treeNode = this.tree.insert({
28 key: hashKey,
29 });
30 link = new LinkList();
31 link.append({ key, value });
32 treeNode.Value.value = link;
33 return this;
34 }
35 get(key) {
36 const hashKey = this.getHashKey(key);
37 const node = this.tree.find({ key: hashKey });
38 if (node) {
39 return node.Value.value;
40 }
41 return null;
42 }
43 getVal(key) {
44 const hashKey = this.getHashKey(key);
45 const node = this.tree.find({ key: hashKey });
46 if (node) {
47 const link = node.Value.value;
48 const val = link.findNode(item => item.key === key);
49 if (!val) {
50 return null;
51 }
52 return val.Value.value;
53 }
54 return null;
55 }
56 clear() {
57 this.size = 0;
58 return this.tree.clear();
59 }
60 remove(key) {
61 const hashKey = this.getHashKey(key);
62 const node = this.get(key);
63 if (node) {
64 const success = node.deleteNode(item => item.key === key);
65 if (success) {
66 this.size--;
67 if (node.Size === 0) {
68 return this.tree.remove({ key: hashKey });
69 }
70 return true;
71 }
72 }
73 return false;
74 }
75 keys() {
76 return BasicBinaryTree.inTraversal(this.tree.Root)
77 .map(item => item.value).reduce((ori, item) => {
78 return ori.concat(item.toArray().map(node => node.Value.key));
79 }, []);
80 }
81 values() {
82 return BasicBinaryTree.inTraversal(this.tree.Root)
83 .map(item => item.value).reduce((ori, item) => {
84 return ori.concat(item.toArray().map(node => node.Value.value));
85 }, []);
86 }
87 contains(key) {
88 return this.tree.contains({ key });
89 }
90 getHashKey(key) {
91 if (typeof key === "number" || typeof key === "string") {
92 return key;
93 }
94 const hashKey = hash(toString(key));
95 return hashKey;
96 }
97}