File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
src/07-object-oriented-design Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ class HashTable {
2+ constructor ( size = 100 ) {
3+ this . size = + size ;
4+ this . table = new Array ( size ) ;
5+ }
6+
7+ set ( key , value ) {
8+ this . table [ this . hash ( key ) ] = value ;
9+ }
10+
11+ get ( key ) {
12+ return this . table [ this . hash ( key ) ] ;
13+ }
14+
15+ hash ( key , max ) {
16+ return JSON . stringify ( key ) . split ( '' ) . reduce ( ( sum , letter ) => sum += letter . charCodeAt ( ) , 0 ) % this . size ;
17+ }
18+ }
19+
20+ module . exports = HashTable ;
Original file line number Diff line number Diff line change 1+ const expect = require ( 'chai' ) . expect ;
2+ const HashTable = require ( './hash-table' ) ;
3+
4+ describe ( 'HashTable' , function ( ) {
5+ it ( 'should set and element and get it' , function ( ) {
6+ const hash = new HashTable ( ) ;
7+ hash . set ( 'adrian' , 100 ) ;
8+ expect ( hash . get ( 'adrian' ) ) . to . equal ( 100 ) ;
9+ } ) ;
10+
11+ it ( 'should set an array as key and get it' , function ( ) {
12+ const hash = new HashTable ( ) ;
13+ hash . set ( [ 10 , 293 ] , 'bomb' ) ;
14+ expect ( hash . get ( [ 10 , 293 ] ) ) . to . equal ( 'bomb' ) ;
15+ } ) ;
16+
17+ it ( 'should take size as parameter' , function ( ) {
18+ const hash = new HashTable ( 1 ) ;
19+ hash . set ( 1 , 'test' ) ;
20+ expect ( hash . get ( 1 ) ) . to . equal ( 'test' ) ;
21+ } ) ;
22+
23+ it ( 'should avoid collisions' , function ( ) {
24+ const hash = new HashTable ( 1 ) ;
25+ hash . set ( 'en' , 'test' ) ;
26+ hash . set ( 'sp' , 'prueba' ) ;
27+ expect ( hash . get ( 'en' ) ) . to . equal ( 'test' ) ;
28+ expect ( hash . get ( 'sp' ) ) . to . equal ( 'prueba' ) ;
29+ } ) ;
30+ } ) ;
You can’t perform that action at this time.
0 commit comments