1
+ function hash ( key , arayLen ) {
2
+ let total = 0 ;
3
+ for ( let char of key ) {
4
+ //map "a" to 1,"b" to 2,"c" to 3,etc.
5
+ let value = char . charCodeAt ( 0 ) - 96 ;
6
+ total = ( total + value ) % arayLen ;
7
+ }
8
+ return total ;
9
+ }
10
+ console . log ( 'without prime hash: ' ) ;
11
+ console . log ( hash ( "pink" , 10 ) ) ;
12
+ console . log ( hash ( "blue" , 10 ) ) ;
13
+ console . log ( hash ( "orangered" , 10 ) ) ;
14
+ console . log ( hash ( "cyan" , 10 ) ) ;
15
+
16
+ /*
17
+ problems of this hash function:
18
+ 1.only hashes string
19
+ 2.not constant time - linear in key length
20
+ 3.could be a little more random
21
+ */
22
+
23
+
24
+ function prime_hash ( key , arayLen ) {
25
+ let total = 0 ;
26
+ let WEIRD_PRIME = 31 ;
27
+ for ( let i = 0 ; i < Math . min ( key . length , 100 ) ; i ++ ) {
28
+ let char = key [ i ] ;
29
+ let value = char . charCodeAt ( 0 ) - 96 ;
30
+ total = ( total * WEIRD_PRIME + value ) % arayLen ;
31
+ }
32
+
33
+ return total ;
34
+ }
35
+ console . log ( 'with prime hash: ' ) ;
36
+ console . log ( prime_hash ( "pink" , 13 ) ) ;
37
+ console . log ( prime_hash ( "blue" , 13 ) ) ;
38
+ console . log ( prime_hash ( "orangered" , 13 ) ) ;
39
+ console . log ( prime_hash ( "cyan" , 13 ) ) ;
40
+
41
+
42
+ /*
43
+ prime number in the hash is helpful in spreading out the keys more uniformly
44
+
45
+ it's also helpful if the array that you're putting values into has a prime length
46
+
47
+ so hash functions use prime numbers
48
+ */
0 commit comments