### Install js-xxhash Source: https://github.com/jason3s/xxhash/blob/main/README.md Install the js-xxhash package using npm. ```bash npm install --save js-xxhash ``` -------------------------------- ### Install Node.js v20 with NVM Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Use NVM to install and switch to Node.js version 20, which is recommended for js-xxhash v5. ```bash nvm install 20 nvm use 20 ``` -------------------------------- ### Import xxHash32 (CommonJS) Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md Example of importing the xxHash32 function using CommonJS syntax. ```javascript const { xxHash32 } = require('js-xxhash'); ``` -------------------------------- ### Hash Table Pre-allocation Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/performance-guide.md For hash table use cases, pre-allocating buffers can be beneficial. This example demonstrates hashing with a pre-allocated buffer and a cached encoder. ```typescript // Hash table: Pre-allocate buffer if possible const buffer = new Uint8Array(1000); const hash1 = xxHash32(data1); // Uses TextEncoder const hash2 = xxHash32(data2); // Cached encoder ``` -------------------------------- ### xxHash32 API Examples Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Illustrates calling xxHash32 with different seeds to show deterministic output. ```typescript xxHash32('text', 0) // → some number xxHash32('text', 1) // → different number ``` -------------------------------- ### Monorepo Import Examples Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Demonstrates how to import the library within a monorepo structure, using either a relative path or the package name. ```typescript // Relative path import import { xxHash32 } from '../../../node_modules/js-xxhash'; // Or via package name (if installed) import { xxHash32 } from 'js-xxhash'; ``` -------------------------------- ### Generate and Log First Hash Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md A basic example showing how to compute a hash for a string and log its hexadecimal representation to the console. ```typescript const hash = xxHash32('Hello, world!'); console.log(hash.toString(16)); // Hex format ``` -------------------------------- ### Install js-xxhash v4 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Install js-xxhash version 4 using npm if you cannot upgrade Node.js. ```bash npm install js-xxhash@^4.0.0 ``` -------------------------------- ### Checking Installed Version via npm CLI Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Demonstrates how to check the installed version of the js-xxhash package using the npm command-line interface. ```bash npm list js-xxhash ``` -------------------------------- ### CommonJS Usage Require Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Shows how to import the xxHash32 function when using CommonJS modules in Node.js. ```javascript // Node.js with .js files in a CommonJS package // or explicit require() const { xxHash32 } = require('js-xxhash'); ``` -------------------------------- ### Import xxHash32 (ESM) Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md Example of importing the xxHash32 function using ES Module syntax. ```typescript import { xxHash32 } from 'js-xxhash'; ``` -------------------------------- ### Project File Structure Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md This diagram shows the organization of the project files, including the README, index, quick reference, API reference, algorithm details, module structure, usage patterns, performance guide, testing validation, and migration compatibility. ```text output/ ├── README.md (this file - navigation) ├── index.md (project overview) ├── quick-reference.md (1-minute lookup) ├── api-reference-xxhash32.md (function reference) ├── algorithm-xxhash32.md (technical internals) ├── module-structure.md (imports/exports) ├── usage-patterns.md (real-world examples) ├── performance-guide.md (benchmarks & optimization) ├── testing-validation.md (testing approach) └── migration-compatibility.md (upgrading versions) ``` -------------------------------- ### XXH32 13-bit Left Rotation Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/algorithm-xxhash32.md Provides a specific example of a 13-bit left rotation applied to a value, demonstrating the bitwise operations used in the algorithm. ```typescript (acc << 13) | (acc >> 19) // 13 + 19 = 32 ``` -------------------------------- ### ESM Usage Import Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Demonstrates how to import the xxHash32 function when using ES modules in Node.js or with .mjs files. ```typescript // Node.js with "type": "module" in package.json // or .mjs files import { xxHash32 } from 'js-xxhash'; ``` -------------------------------- ### Performance Optimization: Pre-encoding for Repeated Hashing Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Example showing that pre-encoding a string to a Buffer can improve performance when hashing the same string many times. ```typescript const buf = Buffer.from(str, 'utf-8'); for (let i = 0; i < 1000; i++) xxHash32(buf); ``` -------------------------------- ### Checking Installed Version via package.json Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Retrieves the installed version of the js-xxhash package by reading its package.json file. ```javascript const pkg = require('js-xxhash/package.json'); console.log(pkg.version); // '5.0.1' ``` -------------------------------- ### Importing from ESM Build Output Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Example of importing the `xxHash32` function from the ESM build output located in `dist/esm/index.js`. This allows for direct imports and potential tree-shaking. ```typescript import { xxHash32 } from 'js-xxhash/dist/esm/index.js'; ``` -------------------------------- ### Content Checksum with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Example of generating a checksum for content using xxHash32 and later verifying its integrity. ```typescript const checksum = xxHash32(content); // Later... if (xxHash32(content) === checksum) { console.log('Content is intact'); } ``` -------------------------------- ### Hash a string with xxHash32 (Browser with CDN) Source: https://github.com/jason3s/xxhash/blob/main/README.md Example of importing xxHash32 in a browser environment using a CDN like jsDelivr. Ensure you replace '{version}' with the actual version number. ```typescript // Using a bundler import { xxHash32 } from 'js-xxhash'; // Using a CDN like jsDelivr import { xxHash32 } from 'https://cdn.jsdelivr.net/npm/js-xxhash@{version}/index.mjs'; let seed = 0; let str = 'My text to hash 😊'; let hashNum = xxHash32(str, seed); console.log(hashNum.toString(16)); ``` -------------------------------- ### XXH32 Bit Rotation Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/algorithm-xxhash32.md Illustrates the general formula for performing a left bit rotation within a 32-bit context, combining left shift and right shift operations. ```typescript (value << n) | (value >> (32 - n)) ``` -------------------------------- ### xxHash32 Seed Behavior Examples Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/algorithm-xxhash32.md Demonstrates how different seed values produce different hash outputs for the same input string. Seed 0 provides the canonical hash. ```typescript xxHash32("data", 0); // One hash value xxHash32("data", 1); // Completely different hash xxHash32("data", 1); // Same as above (deterministic) ``` -------------------------------- ### TypeScript Type Definition Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Shows the signature for the xxHash32 function as defined in the TypeScript type definitions. ```typescript // From index.d.cts export declare function xxHash32(input: Uint8Array | string, seed?: number): number; ``` -------------------------------- ### Bloom Filter Hashing Example Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/performance-guide.md Illustrates using multiple hash functions with different seeds for applications like Bloom filters. This allows for multiple independent hashes of the same item. ```typescript // Bloom filter: Multiple hashes for (let seed = 0; seed < 3; seed++) { bloomFilter.add(xxHash32(item, seed)); } ``` -------------------------------- ### Caching Example for Frequent Reuse Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/performance-guide.md Demonstrates a caching strategy where a hash is computed once and then reused. This is effective when the same content is hashed repeatedly. ```typescript // Caching: Hash once, reuse often const contentHash = xxHash32(largeContent); // One-time cost const hits = new Map(); ``` -------------------------------- ### Hash File Chunks with Sequence Number using xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md This example shows how to hash individual file chunks using xxHash32, incorporating the sequence number into the hash to detect both corruption and reordering. It's suitable for robust file transfer protocols. ```typescript import { xxHash32 } from 'js-xxhash'; interface FileChunk { data: Uint8Array; hash: number; sequenceNumber: number; } function hashChunk(data: Uint8Array, sequenceNumber: number): FileChunk { return { data, // Include sequence number in hash to detect reordered chunks hash: xxHash32(data, sequenceNumber), sequenceNumber, }; } function verifyChunk(chunk: FileChunk): boolean { return chunk.hash === xxHash32(chunk.data, chunk.sequenceNumber); } // Usage const chunk1: FileChunk = hashChunk(new Uint8Array([1, 2, 3]), 0); const chunk2: FileChunk = hashChunk(new Uint8Array([4, 5, 6]), 1); console.log(verifyChunk(chunk1)); // true console.log(verifyChunk(chunk2)); // true ``` -------------------------------- ### Update Package for v3 to v4 Migration Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Install the latest version of js-xxhash (v4.x.x) and be aware that hash outputs may differ, requiring regeneration of cached or stored hashes. ```bash # Step 1: Update package npm install js-xxhash@^4.0.0 ``` -------------------------------- ### Hash Caching with Size Limit Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md Implement a caching strategy with a maximum size to prevent unbounded memory usage. This example uses a simple clear-all eviction policy when the limit is reached. ```typescript import { xxHash32 } from 'js-xxhash'; // Limit cache size to prevent unbounded memory growth function cachedHashWithLimit(input: string, maxCacheSize: number = 10000): number { if (hashCache.has(input)) { return hashCache.get(input)!; } if (hashCache.size >= maxCacheSize) { hashCache.clear(); // Simple eviction strategy } const hash = xxHash32(input); hashCache.set(input, hash); return hash; } ``` -------------------------------- ### xxHash32 Error Handling and Valid Inputs Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Shows examples of valid inputs for xxHash32, including empty strings, null, undefined, and empty buffers. The function handles these inputs gracefully without throwing errors. ```typescript // All valid xxHash32('') // Empty string xxHash32(null) // TypeError (use 'null') xxHash32(undefined) // TypeError (use 'undefined') xxHash32(Buffer.alloc(0)) // Empty buffer, returns hash ``` -------------------------------- ### Install js-xxhash v5.0.0+ on Node.js 20+ Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md If you are using Node.js 20 or later, no code changes are required when upgrading to js-xxhash v5.0.0. Simply update the package. ```bash npm install --save js-xxhash@^5.0.0 # No code changes needed if already on Node 20+ ``` -------------------------------- ### Stay on js-xxhash v4.x for Node.js 18/19 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md If you are on Node.js 18.x/19.x and prefer not to upgrade Node.js, you can pin your js-xxhash installation to the v4 major version. This ensures you continue receiving bug fixes in v4.x. ```bash # Pin to v4 major version npm install --save js-xxhash@^4.0.0 # You'll continue to receive bug fixes in v4.x # New features will only be in v5+ ``` -------------------------------- ### Running Full Test Suite Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md Execute all available tests, including both ESM and integration tests. ```bash npm test ``` -------------------------------- ### Hash Table Implementation with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Shows how to implement a hash table using xxHash32 for key hashing and bucket distribution. ```typescript class Map { private buckets = new Array(256).fill(null).map(() => []); set(key: K, value: V) { const hash = xxHash32(key); const bucket = this.buckets[hash % 256]; // Store [key, value] in bucket } get(key: K): V | undefined { const hash = xxHash32(key); const bucket = this.buckets[hash % 256]; // Find [key, value] in bucket } } ``` -------------------------------- ### Using xxHash32 with TypeScript Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Demonstrates how to import and use xxHash32 with full type support in a TypeScript project. This ensures type safety when calculating hash codes. ```typescript import { xxHash32 } from 'js-xxhash'; function getHashCode(item: string): number { return xxHash32(item); } const code: number = getHashCode('test'); // Correctly typed ``` -------------------------------- ### Basic String Hashing with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/api-reference-xxhash32.md Demonstrates how to hash a simple string using the default seed. ```typescript import { xxHash32 } from 'js-xxhash'; const hash = xxHash32('Hello, world!'); console.log(hash.toString(16)); // e.g., '5e5b6f7d' ``` -------------------------------- ### Using xxHash32 for Hash Table Buckets Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/api-reference-xxhash32.md Shows how to use different seeds with xxHash32 to generate multiple hash functions for distributing keys into hash table buckets. ```typescript import { xxHash32 } from 'js-xxhash'; // Different seeds can be used for multiple hash functions in a hash table const hashFn1 = (key) => xxHash32(key, 0); const hashFn2 = (key) => xxHash32(key, 1); const hashFn3 = (key) => xxHash32(key, 2); // Map keys to different buckets using different hash functions const bucket1 = hashFn1('username') % 256; const bucket2 = hashFn2('username') % 256; ``` -------------------------------- ### Basic Hashing with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Demonstrates hashing a string, a string with a seed, and a byte array using xxHash32. ```typescript import { xxHash32 } from 'js-xxhash'; // Hash a string const hash = xxHash32('Hello, world!'); console.log(hash.toString(16)); // e.g. '5e5b6f7d' // Hash with seed const seeded = xxHash32('data', 42); // Hash a byte array const buffer = Buffer.from('data'); const bufHash = xxHash32(buffer); ``` -------------------------------- ### ESM Entry Point Configuration Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md This JSON snippet shows the configuration for the ESM entry point of the package, `./index.mjs`. This is used by modern bundlers and ES6-aware runtimes. ```json { "export": "./index.mjs" } ``` -------------------------------- ### Running Integration Tests Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md Execute integration tests across multiple environments, including Node.js and browser. ```bash npm run test:integrations ``` -------------------------------- ### Development Build Scripts Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Common npm scripts for building, testing, cleaning, and linting the project. Includes watch mode and performance testing. ```bash # Compile TypeScript to dist/ npm run build # Create CommonJS bundle npm run build:bundle # Run ESM tests npm run test:esm # Run integration tests (Node.js, browser, Electron) npm run test:integrations # Clean build artifacts npm run clean # Full clean build npm run clean-build # Watch mode npm run watch # Performance testing npm run perf # Lint with ESLint npm run lint ``` -------------------------------- ### Basic Usage of xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/index.md Demonstrates how to hash a string with and without a seed, and how to hash a byte array using the xxHash32 function from js-xxhash. ```typescript import { xxHash32 } from 'js-xxhash'; // Hash a string const hash = xxHash32('Hello, world!'); console.log(hash.toString(16)); // Hash with seed const seededHash = xxHash32('Hello, world!', 42); // Hash a byte array const buffer = new Uint8Array([72, 101, 108, 108, 111]); const bufferHash = xxHash32(buffer); ``` -------------------------------- ### GitHub Actions CI Configuration Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md This is a sample GitHub Actions workflow file to automate testing for Node.js projects. It sets up multiple Node.js versions and runs npm test and integration tests. ```yaml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest strategy: matrix: node-version: [20.x, 22.x] steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - run: npm ci - run: npm test - run: npm run test:integrations ``` -------------------------------- ### Converting xxHash32 Output to String Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Shows how to convert the numerical hash output of xxHash32 into different string formats like hex, binary, and decimal. ```typescript const hash = xxHash32('data'); hash.toString(16) // '5e5b6f7d' (hex) hash.toString(2) // '01011110....' (binary) hash.toString(10) // '1586008925' (decimal) ``` -------------------------------- ### Comparing xxHash32 Hashes Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Illustrates how to compare two xxHash32 hashes. Identical inputs with the same seed produce identical hashes, while different inputs typically produce different hashes. ```typescript const h1 = xxHash32('data', 0); const h2 = xxHash32('data', 0); h1 === h2 // true (deterministic) const h3 = xxHash32('other', 0); h1 === h3 // false (usually - collisions are rare) ``` -------------------------------- ### Converting Hash to Hexadecimal Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md Demonstrates how to convert the 32-bit unsigned integer hash output to its hexadecimal string representation. ```typescript const hash = xxHash32('data'); hash.toString(16) // Hex representation ``` -------------------------------- ### CommonJS Import of xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Shows how to import the `xxHash32` function using CommonJS syntax. This is compatible with older Node.js versions and bundlers that support CommonJS. ```javascript const { xxHash32 } = require('js-xxhash'); const hash = xxHash32('data'); ``` -------------------------------- ### Esbuild Command for CommonJS Bundle Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md This bash command shows how esbuild is used to bundle the source code into a CommonJS file for the `dist/cjs/index.cjs` output. It specifies bundling, platform, and target environment. ```bash esbuild --bundle --platform=node --target=node18 --outfile=dist/cjs/index.cjs src/index.ts ``` -------------------------------- ### Upgrade Node.js to 20.x for js-xxhash v5+ Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md If you are on Node.js 18.x/19.x and want to use js-xxhash v5+, upgrade your Node.js version to 20.x using nvm, then update the package and run tests. ```bash # Install Node 20 LTS nvm install 20.x nvm use 20.x # Update package npm install js-xxhash@latest # Verify and test npm test ``` -------------------------------- ### XXH32 Accumulator Initialization (Length < 16 Bytes) Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/algorithm-xxhash32.md For input data shorter than 16 bytes, a single accumulator is initialized using a specific prime constant and the seed. ```plaintext acc = (seed + PRIME32_5) & 0xffffffff ``` -------------------------------- ### Hash a String with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md Demonstrates the basic usage of xxHash32 to hash a string and display its decimal and hexadecimal representations. ```typescript import { xxHash32 } from 'js-xxhash'; const text = 'Hello, world!'; const hash = xxHash32(text); console.log(hash); // 12345678 (example) console.log(hash.toString(16)); // 'bc614e' console.log(hash.toString(2)); // Binary representation ``` -------------------------------- ### Upgrade Verification Checklist Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md A TypeScript function to verify the upgrade by checking function existence, return type, determinism, range, and a known test vector. ```typescript import { xxHash32 } from 'js-xxhash'; function verifyUpgrade() { // Test 1: Function exists and is callable console.assert(typeof xxHash32 === 'function', 'xxHash32 not found'); // Test 2: Returns a number const result = xxHash32('test'); console.assert(typeof result === 'number', 'Result is not a number'); // Test 3: Deterministic const r1 = xxHash32('test'); const r2 = xxHash32('test'); console.assert(r1 === r2, 'Results are not deterministic'); // Test 4: Valid range console.assert(result >= 0 && result <= 0xFFFFFFFF, 'Out of range'); // Test 5: Known test vector (v4.0.0+) const vectorResult = xxHash32('abc').toString(16); console.assert(vectorResult === '32d153ff', `Test vector mismatch: ${vectorResult}`); console.log('✓ All upgrade verification tests passed'); } verifyUpgrade(); ``` -------------------------------- ### XXH32 Accumulator Initialization (Length >= 16 Bytes) Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/algorithm-xxhash32.md When input data is 16 bytes or longer, four parallel accumulators are initialized using the seed and several prime constants. ```plaintext acc1 = (seed + PRIME32_1 + PRIME32_2) & 0xffffffff acc2 = (seed + PRIME32_2) & 0xffffffff acc3 = (seed + 0) & 0xffffffff acc4 = (seed - PRIME32_1) & 0xffffffff ``` -------------------------------- ### CommonJS Entry Point Configuration Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md This JSON snippet details the CommonJS entry point configuration, `./dist/cjs/index.cjs`. It is used for `require('js-xxhash')` in Node.js environments. ```json { "require": "./dist/cjs/index.cjs" } ``` -------------------------------- ### Running ESM Tests Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md Execute the primary test suite for the library using ESM modules. ```bash npm run test:esm ``` -------------------------------- ### Deduplication using xxHash32 and Set Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Demonstrates how to deduplicate items in a list by hashing them and using a Set to track seen hashes. ```typescript const seen = new Set(); const unique = items.filter(item => { const hash = xxHash32(item); if (seen.has(hash)) return false; seen.add(hash); return true; }); ``` -------------------------------- ### Generate Test Coverage Report Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md Command to generate test coverage reports using npm. Reports are available in the terminal, as an HTML file, and as an lcov.info file for external services. ```bash npm run coverage ``` -------------------------------- ### xxHash32 with Different Seeds Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Demonstrates how different seeds produce different hash outputs for the same input. Seeds ensure consistent results for a given input and seed combination. ```typescript const input = 'abc'; xxHash32(input, 0).toString(16) // '32d153ff' xxHash32(input, 1).toString(16) // Different xxHash32(input, 2).toString(16) // Different ``` -------------------------------- ### Hashing a String Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md Demonstrates how to hash a string using xxHash32. The input string is automatically encoded to UTF-8. ```typescript xxHash32('Hello') ``` -------------------------------- ### Simulating 32-bit Arithmetic Overflow Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/algorithm-xxhash32.md Illustrates how to simulate 32-bit unsigned integer overflow in JavaScript using bitwise AND masking with 0xffffffff. This is crucial for maintaining correct hash calculations. ```typescript // Ensure 32-bit overflow const result = (a + b) & 0xffffffff; // Explicitly handle 16-bit multiplications separately const combined = (low * prime) + ((high * prime) << 16); const masked = combined & 0xffffffff; ``` -------------------------------- ### Hashing Uint8Array and Buffer with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Demonstrates hashing binary data using Uint8Array and Node.js Buffer objects. ```typescript xxHash32(new Uint8Array([1, 2, 3])) xxHash32(Buffer.from('data', 'utf-8')) ``` -------------------------------- ### ES Module Import of xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Demonstrates how to import and use the `xxHash32` function in environments supporting ES Modules. This method is suitable for modern browsers and Node.js 20+. ```typescript import { xxHash32 } from 'js-xxhash'; const hash = xxHash32('data'); ``` -------------------------------- ### Integration Test for Upgrade Verification Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md An integration test suite using Chai and js-xxhash to verify hashing of strings and buffers, test vector matching, and seed handling. ```typescript // test/upgrade.test.ts import { expect } from 'chai'; import { xxHash32 } from 'js-xxhash'; describe('Upgrade Verification', () => { it('should hash strings', () => { const hash = xxHash32('data'); expect(typeof hash).to.equal('number'); expect(hash).to.be.within(0, 0xFFFFFFFF); }); it('should hash buffers', () => { const buf = Buffer.from('data'); const hash = xxHash32(buf); expect(typeof hash).to.equal('number'); }); it('should match test vector', () => { expect(xxHash32('abc').toString(16)).to.equal('32d153ff'); }); it('should handle seeds', () => { const h0 = xxHash32('data', 0); const h1 = xxHash32('data', 1); expect(h0).to.not.equal(h1); }); }); ``` -------------------------------- ### Implement Consistent Hashing Ring with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md This consistent hashing ring implementation uses xxHash32 to distribute keys (e.g., requests) across a set of servers. It minimizes remapping when servers are added or removed, making it ideal for load balancing. ```typescript import { xxHash32 } from 'js-xxhash'; class ConsistentHashRing { private ring = new Map(); // hash -> server private servers: string[] = []; addServer(server: string): void { this.servers.push(server); // Add multiple points on the ring per server (virtual nodes) for (let i = 0; i < 160; i++) { const key = `${server}#${i}`; const hash = xxHash32(key); this.ring.set(hash, server); } } getServer(key: string): string | undefined { if (this.ring.size === 0) return undefined; const hash = xxHash32(key); const sortedHashes = Array.from(this.ring.keys()).sort((a, b) => a - b); // Find the first hash >= the key's hash const nextHash = sortedHashes.find(h => h >= hash) || sortedHashes[0]; return this.ring.get(nextHash); } } // Usage const ring = new ConsistentHashRing(); ring.addServer('server1'); ring.addServer('server2'); ring.addServer('server3'); console.log(ring.getServer('user:123')); // Consistent server for this user console.log(ring.getServer('user:456')); // Likely different server console.log(ring.getServer('user:123')); // Same as first call ``` -------------------------------- ### Using a Seed for Different Hashes Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/README.md Illustrates how to use the optional seed parameter to generate different hash outputs for the same input data. This is useful for creating multiple independent hash functions or for salted hashing. ```typescript xxHash32('data', 0) // One hash xxHash32('data', 1) // Different hash xxHash32('data', 0) // Same as first ``` -------------------------------- ### Dual Module Support Configuration Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Configures package.json to support both CommonJS and ES modules in Node.js environments. Specifies entry points for 'import' and 'require'. ```json { "type": "module", "exports": { ".": { "import": "./index.mjs", "require": "./dist/cjs/index.cjs", "types": "./dist/cjs/index.d.cts" } } } ``` -------------------------------- ### Using xxHash32 Hashes in Collections Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Illustrates how to use the numerical hash values as keys in a Map, elements in a Set, or indices in an array. ```typescript // Map key const hashMap = new Map(); hashMap.set(xxHash32('key'), 'value'); // Set element const hashSet = new Set(); hashSet.add(xxHash32('item')); // Array index (modulo size) const array = new Array(256); const index = xxHash32('key') % 256; ``` -------------------------------- ### Content-Based Cache Key with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md Demonstrates creating a cache where keys are generated by hashing the JSON string representation of an object. This allows for content-based caching. ```typescript import { xxHash32 } from 'js-xxhash'; class Cache { private data = new Map(); set(key: K, value: V): void { const hash = xxHash32(JSON.stringify(key)); if (!this.data.has(hash)) { this.data.set(hash, []); } const bucket = this.data.get(hash)!; const existing = bucket.find(item => JSON.stringify(item.key) === JSON.stringify(key)); if (existing) { existing.value = value; } else { bucket.push({ key, value }); } } get(key: K): V | undefined { const hash = xxHash32(JSON.stringify(key)); const bucket = this.data.get(hash); return bucket?.find(item => JSON.stringify(item.key) === JSON.stringify(key))?.value; } } // Usage const cache = new Cache<{id: number}, string>(); cache.set({id: 1}, 'User One'); console.log(cache.get({id: 1})); // 'User One' ``` -------------------------------- ### Migrate to js-xxhash v5.0.0 on Node.js 18/19 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md For users on Node.js 18.x or 19.x, you have two options: upgrade Node.js to version 20+ or stay on js-xxhash v4.x. ```bash # Option 1: Upgrade Node.js nvm install 20 nvm use 20 npm install --save js-xxhash@^5.0.0 # Option 2: Stay on v4 npm install --save js-xxhash@^4.0.0 ``` -------------------------------- ### Custom Seed Behavior Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Demonstrates how different seeds produce different hash values for the same input, and that the same seed is deterministic. ```typescript xxHash32('data', 0) // One value xxHash32('data', 1) // Different value xxHash32('data', 1) // Same as second (deterministic) xxHash32('data', -1) // Another value (32-bit unsigned) ``` -------------------------------- ### Verify Node.js Version for v4 to v5 Migration Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Ensure your Node.js version is 20.0.0 or later before upgrading to js-xxhash v5. Update Node.js if necessary. ```bash # Step 1: Verify Node.js version node --version # Must be v20.0.0 or later ``` ```bash # Step 2: Update if needed nvm install 20 nvm use 20 node --version # Verify: v20.x.x ``` -------------------------------- ### Troubleshoot Node.js Version Incompatibility with v5 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md js-xxhash v5 requires Node.js version 20.0.0 or later. Verify your current Node.js version and update if it is older. ```bash # Verify your version node --version ``` -------------------------------- ### Hash Byte Arrays with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md Shows how to hash different byte array representations, including Node.js Buffers, typed arrays, and ArrayBuffers. ```typescript import { xxHash32 } from 'js-xxhash'; // From Buffer (Node.js) const buffer = Buffer.from('data', 'utf-8'); const hash = xxHash32(buffer); // From typed array const uint8 = new Uint8Array([1, 2, 3, 4, 5]); const hash2 = xxHash32(uint8); // From ArrayBuffer const arrayBuffer = new ArrayBuffer(4); const view = new Uint8Array(arrayBuffer); view[0] = 0xFF; const hash3 = xxHash32(view); ``` -------------------------------- ### Create and Verify Data Blocks with xxHash32 Checksum Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md This snippet demonstrates how to create data blocks with an embedded checksum using xxHash32 and verify their integrity. It's useful for detecting accidental data corruption. ```typescript import { xxHash32 } from 'js-xxhash'; interface DataBlock { content: string; checksum: number; } function createBlock(content: string): DataBlock { return { content, checksum: xxHash32(content, 0), }; } function verifyBlock(block: DataBlock): boolean { const recalculatedChecksum = xxHash32(block.content, 0); return block.checksum === recalculatedChecksum; } // Usage const block = createBlock('Important data'); console.log(verifyBlock(block)); // true block.content = 'Modified data'; console.log(verifyBlock(block)); // false - corruption detected ``` -------------------------------- ### Version Pinning: Allow Minor/Patch Updates Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Pin js-xxhash to a major version (e.g., 5.x.x) in dependencies to allow minor and patch updates, preventing breaking changes from major version upgrades. Recommended for libraries. ```json { "dependencies": { "js-xxhash": "^5.0.0" } } ``` -------------------------------- ### Browser CDN Import of xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Illustrates importing the `xxHash32` function directly from a CDN using an ES Module import. This is useful for including the library in web pages without a build process. ```typescript import { xxHash32 } from 'https://cdn.jsdelivr.net/npm/js-xxhash@5.0.1/index.mjs'; const hash = xxHash32('data'); ``` -------------------------------- ### Compare String vs. Buffer Hashing Performance Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/performance-guide.md Identify whether string encoding or the hashing operation itself is the performance bottleneck by comparing hashing times for strings versus pre-encoded buffers. This helps in optimizing for high-performance scenarios. ```typescript // Is encoding or hashing the bottleneck? const text = 'Sample text'; const encoded = new TextEncoder().encode(text); const start1 = performance.now(); for (let i = 0; i < 100000; i++) { xxHash32(text); } const stringTime = performance.now() - start1; const start2 = performance.now(); for (let i = 0; i < 100000; i++) { xxHash32(encoded); } const bufferTime = performance.now() - start2; console.log(`String time: ${stringTime}ms`); console.log(`Buffer time: ${bufferTime}ms`); console.log(`Encoding overhead: ${stringTime - bufferTime}ms (${((stringTime - bufferTime) / stringTime * 100).toFixed(1)}%)`); ``` -------------------------------- ### Importing xxHash32 from Browser CDN Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Import statement for using xxHash32 directly from a CDN in a browser environment. ```typescript import { xxHash32 } from 'https://cdn.jsdelivr.net/npm/js-xxhash@5.0.1/index.mjs'; ``` -------------------------------- ### Multiple Hash Functions with Different Seeds Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Illustrates generating multiple distinct hashes for the same data by using different seeds with xxHash32. ```typescript const h1 = xxHash32(data, 0); const h2 = xxHash32(data, 1); const h3 = xxHash32(data, 2); // Use for bloom filters, cuckoo hashing, etc. ``` -------------------------------- ### Advanced Import of UTF-8 Encoding Utilities Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md Demonstrates importing and using UTF-8 encoding utility functions directly from the source code. These are not part of the public API and may change. ```typescript // From source code (may require build configuration) import { toUtf8, toUtf8_1, toUtf8_2, toUtf8_3 } from 'js-xxhash/src/toUtf8.js'; const bytes: Uint8Array = toUtf8('Hello, world!'); ``` -------------------------------- ### Hashing Node.js Buffers with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/api-reference-xxhash32.md Demonstrates hashing a Node.js Buffer object, which is compatible with Uint8Array. ```typescript import { xxHash32 } from 'js-xxhash'; const buffer = Buffer.from('My text to hash 😊', 'utf-8'); const hash = xxHash32(buffer); console.log(hash.toString(16)); // 'af7fd356' ``` -------------------------------- ### Primary Export of xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/module-structure.md This snippet shows the main entry point export for the `js-xxhash` package, which is the `xxHash32` function. This is the intended public API. ```typescript export { xxHash32 } from './xxHash32.js'; ``` -------------------------------- ### Version Pinning: Receive Security Patches Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Pin js-xxhash to a minor version (e.g., 5.0.x) to receive security patches while locking the major and minor versions. Recommended for applications. ```json { "dependencies": { "js-xxhash": "~5.0.1" } } ``` -------------------------------- ### Version Pinning: Lock Exact Version Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md Pin js-xxhash to an exact version (e.g., 5.0.1) for strict environments. This requires manual updates for all changes. Recommended for strict environments. ```json { "dependencies": { "js-xxhash": "5.0.1" } } ``` -------------------------------- ### Troubleshoot 'Cannot find module' Error Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md If you encounter a 'Cannot find module' error after upgrading, clear your node_modules and package-lock.json, then reinstall dependencies. ```bash # Solution: Clear node_modules and reinstall rm -rf node_modules package-lock.json npm install ``` -------------------------------- ### Hash Table with Multiple Hash Functions Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/usage-patterns.md Illustrates using different seeds with xxHash32 to generate multiple hash values for implementing collision-resistant hash tables like cuckoo hashing. ```typescript import { xxHash32 } from 'js-xxhash'; class MultiHashTable { private buckets1: Map = new Map(); private buckets2: Map = new Map(); private buckets3: Map = new Map(); private hash1(key: string): number { return xxHash32(key, 0); } private hash2(key: string): number { return xxHash32(key, 1); } private hash3(key: string): number { return xxHash32(key, 2); } set(key: string, value: V): void { // Try to place in least-occupied bucket const buckets = [this.buckets1, this.buckets2, this.buckets3]; const idx = buckets.findIndex(b => !b.has(this.hash(key) % 1024 as unknown as string)); if (idx >= 0) { buckets[idx].set(key, value); } } } ``` -------------------------------- ### Performance Optimization: Using Uint8Array for Binary Data Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/quick-reference.md Recommends using Uint8Array directly when the input data is already in binary format to avoid encoding overhead. ```typescript xxHash32(uint8array) // No encoding needed ``` -------------------------------- ### Upgrade js-xxhash to Latest on Node.js 20+ Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/migration-compatibility.md For users on Node.js 20+, update the js-xxhash package to the latest version. No code changes are necessary. Run tests and build to verify. ```bash # Update package npm install js-xxhash@latest # No code changes needed npm test npm run build ``` -------------------------------- ### Property-Based Testing for xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md Uses fast-check to verify properties like determinism, input sensitivity, output range, and seed sensitivity for xxHash32. ```typescript import fc from 'fast-check'; import { xxHash32 } from 'js-xxhash'; describe('xxHash32 Properties', () => { it('should be deterministic', () => { fc.assert( fc.property(fc.string(), fc.integer({ min: 0, max: 1000 }), (str, seed) => { const hash1 = xxHash32(str, seed); const hash2 = xxHash32(str, seed); return hash1 === hash2; }) ); }); it('should be sensitive to input changes', () => { fc.assert( fc.property(fc.string({ minLength: 1 }), (str) => { const hash1 = xxHash32(str); const modified = str.slice(1) + 'X'; const hash2 = xxHash32(modified); // Almost always different (collision probability is negligible) return hash1 !== hash2; }), { numRuns: 100 } ); }); it('should produce 32-bit unsigned integers', () => { fc.assert( fc.property(fc.string(), fc.integer(), (str, seed) => { const hash = xxHash32(str, seed); return hash >= 0 && hash <= 4294967295 && Number.isInteger(hash); }) ); }); it('should be seed-sensitive', () => { fc.assert( fc.property(fc.string(), (str) => { const hash0 = xxHash32(str, 0); const hash1 = xxHash32(str, 1); return hash0 !== hash1; }), { numRuns: 100 } ); }); }); ``` -------------------------------- ### Performance Testing for xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/testing-validation.md Verifies the speed of xxHash32 for small and large inputs within unit tests. ```typescript describe('Performance', () => { it('should hash small strings quickly', () => { const iterations = 10000; const start = performance.now(); for (let i = 0; i < iterations; i++) { xxHash32('test'); } const duration = performance.now() - start; const opsPerSecond = iterations / (duration / 1000); // Should achieve at least 100K ops/sec even on slow hardware expect(opsPerSecond).to.be.above(100000); }); it('should handle large inputs', () => { const largeString = 'x'.repeat(1000000); const start = performance.now(); xxHash32(largeString); const duration = performance.now() - start; // Should complete in reasonable time (< 1 second for 1MB) expect(duration).to.be.below(1000); }); }); ``` -------------------------------- ### Hashing Byte Arrays with xxHash32 Source: https://github.com/jason3s/xxhash/blob/main/_autodocs/api-reference-xxhash32.md Illustrates hashing a Uint8Array, representing raw byte data. ```typescript import { xxHash32 } from 'js-xxhash'; const buffer = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]); // "Hello" const hash = xxHash32(buffer); console.log(hash.toString(16)); ```