Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active April 20, 2019 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/7f56f3cff02308884bb10591d64a5d94 to your computer and use it in GitHub Desktop.
Save dfkaye/7f56f3cff02308884bb10591d64a5d94 to your computer and use it in GitHub Desktop.
javascript implementation of java's string.hashcode() method
// 2 April 2019
// hashcode algo
// from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
// stolen from jjdubray
// see https://medium.com/@metapgmr/hex-a-no-framework-approach-to-building-modern-web-apps-e43f74190b9c
function hashCode(s) {
var h = 0
return !s || !s.length
? h
: String(s).split('').reduce(function(h, c) {
return ((h << 5) - h) + c.charCodeAt(0) << 0
}, h);
}
var tests = [
null, undefined, , '', false, 0, NaN,
true,
'hello',
{
h: 'h', e: 'e', l: 'l', o: 'o'
},
[
'hello'
],
[
'h','e', 'l', 'l', 'o'
]
];
var results = tests.map(function(test) {
return { input: test, result: hashCode(test) };
})
console.log(
JSON.stringify(results, null, 2)
);
/*
[
{
"input": null,
"result": 0
},
{
"result": 0
},
null,
{
"input": "",
"result": 0
},
{
"input": false,
"result": 0
},
{
"input": 0,
"result": 0
},
{
"input": null,
"result": 0
},
{
"input": true,
"result": 0
},
{
"input": "hello",
"result": 99162322
},
{
"input": {
"h": "h",
"e": "e",
"l": "l",
"o": "o"
},
"result": 0
},
{
"input": [
"hello"
],
"result": 99162322
},
{
"input": [
"h",
"e",
"l",
"l",
"o"
],
"result": 1181937828
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment