字典,就是以 [键, 值] 的形式来存储元素,也常叫 映射Map

    1. class ValuePair {
    2. constructor(key, value) {
    3. this.key = key;
    4. this.value = value;
    5. }
    6. toString() {
    7. return `[#${this.key}: ${this.value}]`;
    8. }
    9. }
    10. class Dictionary {
    11. constructor() {
    12. this.table = {};
    13. }
    14. toStrFn(item) {
    15. if (item === null) {
    16. return 'NULL';
    17. } else if (item === undefined) {
    18. return 'UNDEFINED';
    19. } else if (typeof item === 'string' || item instanceof String) {
    20. return `${item}`;
    21. }
    22. return item.toString();
    23. }
    24. set(key, value) {
    25. if (key != null && value != null) {
    26. const tableKey = this.toStrFn(key);
    27. this.table[tableKey] = new ValuePair(key, value);
    28. return true;
    29. }
    30. return false;
    31. }
    32. remove(key) {
    33. if (this.hasKey(key)) {
    34. delete this.table[this.toStrFn(key)];
    35. return true;
    36. }
    37. return false;
    38. }
    39. hasKey(key) {
    40. return this.table[this.toStrFn(key)] ? true : false;
    41. }
    42. get(key) {
    43. const valuePair = this.table[this.toStrFn(key)];
    44. return valuePair ? valuePair.value : undefined;
    45. }
    46. clear() {
    47. this.table = {};
    48. }
    49. size() {
    50. return Object.keys(this.table).length;
    51. }
    52. isEmpty() {
    53. return this.size() === 0;
    54. }
    55. keys() {
    56. return this.keyValues().map(item => item.key);
    57. }
    58. values() {
    59. return this.keyValues().map(item => item.value);
    60. }
    61. keyValues() {
    62. return Object.values(this.table);
    63. }
    64. forEach(callback) {
    65. const valuePair = this.keyValues();
    66. for (let i = 0; i < valuePair.length; i++) {
    67. const result = callback(valuePair[i].key, valuePair[i].value);
    68. if (!result) break;
    69. }
    70. }
    71. }
    72. const dictionary = new Dictionary();
    73. dictionary.set('Gandalf', 'gandalf@email.com');
    74. dictionary.set('John', 'johnsnow@email.com');
    75. dictionary.set('Tyrion', 'tyrion@email.com');
    76. console.log(dictionary.get('John'))