File tree Expand file tree Collapse file tree 2 files changed +25
-7
lines changed
src/07-object-oriented-design Expand file tree Collapse file tree 2 files changed +25
-7
lines changed Original file line number Diff line number Diff line change 1+ const t = JSON . stringify ;
2+
13class HashTable {
24 constructor ( size = 100 ) {
35 this . size = + size ;
@@ -13,18 +15,25 @@ class HashTable {
1315
1416 get ( key ) {
1517 const bucket = this . table [ this . hash ( key ) ] ;
18+ if ( ! bucket ) { return ; }
1619
17- if ( bucket ) {
18- for ( let b of bucket ) {
19- if ( JSON . stringify ( b . key ) === JSON . stringify ( key ) ) {
20- return b . value ;
21- }
20+ for ( let b of bucket ) {
21+ if ( t ( b . key ) === t ( key ) ) {
22+ return b . value ;
2223 }
2324 }
2425 }
2526
26- hash ( key , max ) {
27- return JSON . stringify ( key ) . split ( '' ) . reduce ( ( sum , letter ) => sum += letter . charCodeAt ( ) , 0 ) % this . size ;
27+ remove ( key ) {
28+ const bucket = this . table [ this . hash ( key ) ] ;
29+ if ( ! bucket ) { return ; }
30+
31+ const index = bucket . findIndex ( ( b ) => t ( b . key ) === t ( key ) ) ;
32+ bucket . splice ( index , 1 ) ;
33+ }
34+
35+ hash ( key ) {
36+ return t ( key ) . split ( '' ) . reduce ( ( sum , letter ) => sum += letter . charCodeAt ( ) , 0 ) % this . size ;
2837 }
2938}
3039
Original file line number Diff line number Diff line change @@ -34,4 +34,13 @@ describe('HashTable', function() {
3434 expect ( hash . get ( 'en' ) ) . to . equal ( 'test' ) ;
3535 expect ( hash . get ( 'sp' ) ) . to . equal ( 'prueba' ) ;
3636 } ) ;
37+
38+ it ( 'should remove elements' , function ( ) {
39+ const hash = new HashTable ( 1 ) ;
40+ hash . set ( 'sp' , 'prueba' ) ;
41+ hash . set ( 'en' , 'test' ) ;
42+ hash . remove ( 'en' ) ;
43+ expect ( hash . get ( 'en' ) ) . to . equal ( undefined ) ;
44+ expect ( hash . get ( 'sp' ) ) . to . equal ( 'prueba' ) ;
45+ } ) ;
3746} ) ;
You can’t perform that action at this time.
0 commit comments