mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-13 16:19:46 +08:00
feat(chapter_hashing): Add js and ts codes for chapter hashing (#675)
* 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
This commit is contained in:
60
codes/javascript/chapter_hashing/simple_hash.js
Normal file
60
codes/javascript/chapter_hashing/simple_hash.js
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 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);
|
||||
Reference in New Issue
Block a user