目的:ES6标准下的JS数据结构的一些实现代码。(作为记录和启发)
内容:字典和散列表。(未完成,待继续)
一、基础数据结构
1、字典(以[键,值]对的形式存储数据,table[key]={key, value})
//注:由于JavaScript不是强类型的语言,不能保证键一定是字符串,所以需要把所有键名的传入的对象转换为字符串,使得Dictionary类中搜索和获取值更简单。
1 class ValuePair { 2 constructor(key, value) { 3 this.key = key; 4 this.value = value; 5 } 6 7 toString() { 8 return `[#${this.key}: ${this.value}]`; 9 } 10 } 11 12 function defaultToString(item) { 13 if (item === null) { 14 return 'NULL'; 15 } if (item === undefined) { 16 return 'UNDEFINED'; 17 } if (typeof item === 'string' || item instanceof String) { 18 return `${item}`; 19 } 20 return item.toString(); 21 } 22 23 class Dictionary { 24 constructor(toStrFn = defaultToString) { 25 this.toStrFn = toStrFn; 26 this.table = {}; 27 } 28 hasKey(key) { 29 return this.table[this.toStrFn(key)] != null; 30 } 31 set(key, value) { 32 if (key != null && value != null) { 33 const tableKey = this.toStrFn(key); 34 this.table[tableKey] = new ValuePair(key,value); 35 return true; 36 } 37 return false; 38 } 39 remove(key) { 40 if (this.hasKey(key)) { 41 delete this.table[this.toStrFn(key)]; 42 return true; 43 } 44 return false; 45 } 46 get(key) { 47 const valuePair = this.table[this.toStrFn(key)]; 48 return valuePair == null ? undefined : valuePair.value; 49 } 50 keyValues() { 51 return Object.values(this.table); 52 } 53 values() { 54 return this.keyValues().map(valuePair => valuePair.value); 55 } 56 57 keys() { 58 return this.keyValues().map(valuePair => valuePair.key); 59 } 60 forEach(callbackFn) { 61 const valuePairs = this.keyValues(); 62 for (let i = 0; i < valuePairs.length; i++) { 63 const result = callbackFn(valuePairs[i].key, valuePairs[i].value); 64 if (result === false) { 65 break; 66 } 67 } 68 } 69 70 isEmpty() { 71 return this.size() === 0; 72 } 73 74 size() { 75 return Object.keys(this.table).length; 76 } 77 78 clear() { 79 this.table = {}; 80 } 81 82 toString() { 83 if (this.isEmpty()) { 84 return ''; 85 } 86 const valuePairs = this.keyValues(); 87 let objString = `${valuePairs[0].toString()}`; 88 for (let i = 1; i < valuePairs.length; i++) { 89 objString = `${objString},${valuePairs[i].toString()}`; 90 } 91 return objString; 92 } 93 94 95 } 96 97 const dictionary = new Dictionary(); 98 dictionary.set('Bob','student'); 99 dictionary.set('Alice','teacher'); 100 dictionary.set('Jack','student'); 101 console.log(dictionary); 102 console.log(dictionary.hasKey('Bob')); 103 dictionary.remove('Jack'); 104 console.log(dictionary); 105 console.log(dictionary.get('Alice')); 106 console.log(dictionary.keyValues()); 107 console.log(dictionary.keys()); 108 console.log(dictionary.values()); 109 dictionary.forEach((k, v) => { 110 console.log(`forEach: `, `key: ${k},value: ${v}`); 111 });
2、散列表(HashTable类或HashMap类,它是Dictionary类的一种散列表实现方式)
二、简单应用