Skip to content

Commit

Permalink
Add hashString
Browse files Browse the repository at this point in the history
  • Loading branch information
AlttiRi committed Jul 13, 2024
1 parent d5fddae commit 9f90d1d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@alttiri/util-js",
"version": "1.12.0-20240713",
"version": "1.13.0-20240713",
"description": "Some util functions for personal use",
"homepage": "https://github.com/AlttiRi/util-js",
"keywords": [
Expand Down
17 changes: 17 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,20 @@ export function isString(value: unknown): value is string {
export function isAnyString(value: unknown): value is (string | String) {
return typeof value === "string" || value instanceof String;
}
/**
* Java's `hashCode` like.
* @example
* hashString("Lorem Ipsum") === -488052133
* hashString("Qwerty") === -1862984904
* hashString("A") === 65
* hashString("👾👽💀") === -2019372252
* @param {string} str
* @return {number}
*/
export function hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = Math.imul(Math.imul(31, hash) + str.charCodeAt(i), 1);
}
return hash;
}

0 comments on commit 9f90d1d

Please sign in to comment.