From 46daaf51c5feb3e4fae17988fcd40fe9f55c084d Mon Sep 17 00:00:00 2001 From: JD Medina Date: Thu, 10 Dec 2020 23:54:37 -0800 Subject: [PATCH] Modify HashTable (#447) Add a getValues() method to the HashTable data structure --- src/data-structures/hash-table/HashTable.js | 12 ++++++++++++ .../hash-table/__test__/HashTable.test.js | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/data-structures/hash-table/HashTable.js b/src/data-structures/hash-table/HashTable.js index 5e19e7b7..6ac83a52 100644 --- a/src/data-structures/hash-table/HashTable.js +++ b/src/data-structures/hash-table/HashTable.js @@ -105,4 +105,16 @@ export default class HashTable { getKeys() { return Object.keys(this.keys); } + + /** + * Gets the list of all the stored values in the hash table in the order of + * the keys map. + * + * @return {*[]} + */ + getValues() { + const keys = this.getKeys(); + + return keys.map(key => this.buckets[this.hash(key)].head.value.value); + } } diff --git a/src/data-structures/hash-table/__test__/HashTable.test.js b/src/data-structures/hash-table/__test__/HashTable.test.js index 27d590cf..cc8d45d5 100644 --- a/src/data-structures/hash-table/__test__/HashTable.test.js +++ b/src/data-structures/hash-table/__test__/HashTable.test.js @@ -86,4 +86,14 @@ describe('HashTable', () => { expect(hashTable.has('b')).toBe(true); expect(hashTable.has('x')).toBe(false); }); + + it('should get all the values', () => { + const hashTable = new HashTable(3); + + hashTable.set('a', 'alpha'); + hashTable.set('b', 'beta'); + hashTable.set('c', 'gamma'); + + expect(hashTable.getValues()).toEqual(['alpha', 'beta', 'gamma']); + }); });