From 3064dac005f82c897001ecc68fcd73cc8472f26a Mon Sep 17 00:00:00 2001 From: Xinyu Ma Date: Sun, 29 Sep 2024 13:09:05 -0700 Subject: [PATCH] Add string hash --- package.json | 2 +- src/utils/fnv-hash.ts | 19 +++++++++++++++++++ src/utils/mod.ts | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 src/utils/fnv-hash.ts diff --git a/package.json b/package.json index 7160b2b..d65f260 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ucla-irl/ndnts-aux", - "version": "3.0.4", + "version": "3.0.5", "description": "NDNts Auxiliary Package for Web and Deno", "scripts": { "test": "deno test --no-check", diff --git a/src/utils/fnv-hash.ts b/src/utils/fnv-hash.ts new file mode 100644 index 0000000..6f133f2 --- /dev/null +++ b/src/utils/fnv-hash.ts @@ -0,0 +1,19 @@ +/** + * Calculate a 32 bit FNV-1a hash + * Found here: https://gist.github.com/vaiorabbit/5657561 + * Ref.: http://isthe.com/chongo/tech/comp/fnv/ + * + * @param str Input string to hash + * @param seed The seed. By default `0x811c9dc5` is used. + * @returns The FNV-1a hash in a 32bit number. + */ +export const hashFnv32a = (str: string, seed?: number): number => { + /*jshint bitwise:false */ + let hval = seed ?? 0x811c9dc5; + + for (let i = 0, l = str.length; i < l; i++) { + hval ^= str.charCodeAt(i); + hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); + } + return hval >>> 0; +}; diff --git a/src/utils/mod.ts b/src/utils/mod.ts index 1b23383..a9ff05f 100644 --- a/src/utils/mod.ts +++ b/src/utils/mod.ts @@ -11,3 +11,4 @@ export * from './disposable-stacks.ts'; export * from './responder.ts'; export * from './event-chain.ts'; export * from './random-uuid.ts'; +export * from './fnv-hash.ts';