Skip to content

Commit

Permalink
Add hashing function (based on djb2) to util #2027
Browse files Browse the repository at this point in the history
  • Loading branch information
maxkfranz committed Dec 8, 2017
1 parent 2aa209f commit fb47597
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/util/hash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
let hashIterableInts = function( iterator, seed = 5381 ){ // djb2/string-hash
let hash = seed;
let entry;

for( ;; ){
entry = iterator.next();

if( entry.done ){ break; }

hash = (hash * 33) ^ entry.value;
}

return hash >>> 0;
};

let hashString = function( str, seed ){
let entry = { value: 0, done: false };
let i = 0;
let length = str.length;

let iterator = {
next(){
if( i < length ){
entry.value = str.charCodeAt(i++);
} else {
entry.done = true;
}

return entry;
}
};

return hashIterableInts( iterator, seed );
};

module.exports = { hashIterableInts, hashString };
3 changes: 2 additions & 1 deletion src/util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ util.setPrefixedProperty = function( obj, propName, prefix, value ){
require( './regex' ),
require( './strings' ),
require( './timing' ),
require( './sort' )
require( './sort' ),
require( './hash' )
].forEach( function( req ){
util.extend( util, req );
} );
Expand Down

0 comments on commit fb47597

Please sign in to comment.