-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathhashcode.js
62 lines (46 loc) · 1.2 KB
/
hashcode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Used to check objects for own properties
const hasOwnProperty = Object.prototype.hasOwnProperty
// Hashes a string
const hash = (string) => {
let hash = 0
string = string.toString()
for(let i = 0; i < string.length; i++)
{
hash = (((hash << 5) - hash) + string.charCodeAt(i)) & 0xFFFFFFFF
}
return hash
}
// Deep hashes an object
const object = (obj) => {
//
if(typeof obj.getTime == 'function')
{
return obj.getTime()
}
let result = 0
for(let property in obj)
{
if(hasOwnProperty.call(obj, property))
{
result += hash(property + value(obj[property]))
}
}
return result
}
const value = (value) => {
const type = value == undefined ? undefined : typeof value
// Does a type check on the passed in value and calls the appropriate hash method
return MAPPER[type] ? MAPPER[type](value) + hash(type) : 0
}
const MAPPER =
{
string: hash,
number: hash,
boolean: hash,
object: object
// functions are excluded because they are not representative of the state of an object
// types 'undefined' or 'null' will have a hash of 0
}
module.exports = {
value: value,
}