mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 23:36:28 +08:00
e97eee0e18
* refactor(chapter_hashing): Remove unnecessary chaining operator * feat(chapter_hashing): Add js and ts codes for chapter 6 * refactor(chapter_hashing): Optimize the remove function logic * refactor(chapter_hashing): Remove unnecessary chaining operator * refactor(chapter_hashing): use const instead of let
60 lines
1.2 KiB
JavaScript
60 lines
1.2 KiB
JavaScript
/**
|
|
* File: simple_hash.js
|
|
* Created Time: 2023-08-06
|
|
* Author: yuan0221 (yl1452491917@gmail.com)
|
|
*/
|
|
|
|
/* 加法哈希 */
|
|
function addHash(key) {
|
|
let hash = 0;
|
|
const MODULUS = 1000000007;
|
|
for (const c of key) {
|
|
hash = (hash + c.charCodeAt(0)) % MODULUS;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
/* 乘法哈希 */
|
|
function mulHash(key) {
|
|
let hash = 0;
|
|
const MODULUS = 1000000007;
|
|
for (const c of key) {
|
|
hash = (31 * hash + c.charCodeAt(0)) % MODULUS;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
/* 异或哈希 */
|
|
function xorHash(key) {
|
|
let hash = 0;
|
|
const MODULUS = 1000000007;
|
|
for (const c of key) {
|
|
hash ^= c.charCodeAt(0);
|
|
}
|
|
return hash & MODULUS;
|
|
}
|
|
|
|
/* 旋转哈希 */
|
|
function rotHash(key) {
|
|
let hash = 0;
|
|
const MODULUS = 1000000007;
|
|
for (const c of key) {
|
|
hash = ((hash << 4) ^ (hash >> 28) ^ c.charCodeAt(0)) % MODULUS;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
/* Driver Code */
|
|
const key = 'Hello 算法';
|
|
|
|
let hash = addHash(key);
|
|
console.log('加法哈希值为 ' + hash);
|
|
|
|
hash = mulHash(key);
|
|
console.log('乘法哈希值为 ' + hash);
|
|
|
|
hash = xorHash(key);
|
|
console.log('异或哈希值为 ' + hash);
|
|
|
|
hash = rotHash(key);
|
|
console.log('旋转哈希值为 ' + hash);
|