@nap5/gnrng-id v0.1.4
@nap5/gnrng-id
GNRNG (Good Night Random Number Generator) with ID generation utilities powered by WebAssembly and Rust.
High-performance, deterministic random number generation and ID utilities for modern JavaScript/TypeScript applications.
โจ Features
- ๐ฆ Rust + WebAssembly: High-performance core implementation
- ๐ Deterministic: Seed-based reproducible random generation
- ๐ ID Generation: Safe, collision-resistant ID creation
- ๐ฆ Dual Publishing: Available on both npm and JSR
- ๐ Universal: Works in Node.js, Deno, and browsers
- โก Fast: Batch operations for optimal FFI performance
- ๐ง Type Safe: Full TypeScript support with generated types
- ๐งช Well Tested: Comprehensive test suite with benchmarks
๐ Installation
npm
npm install @nap5/gnrng-idJSR (for Deno)
deno add npm:@nap5/gnrng-idBrowser (CDN)
<script type="module">
import { createId, createIdBySeed } from 'https://esm.sh/@nap5/gnrng-id'
</script>โก Quick Start
Basic Usage
import { initWasm, createId, createIdBySeed, Gnrng, IdType } from '@nap5/gnrng-id'
// Initialize WASM module (required before first use)
await initWasm()
// Generate random IDs
const randomId = createId() // "t_A7Bp9X2"
const userId = createId(8, IdType.User) // "u_K3mN9Pq5"
// Generate deterministic IDs
const deterministicId = createIdBySeed('my-seed') // Always same result
const projectId = createIdBySeed('project-alpha', 10, IdType.Project) // "p_X9kM2nQ8vB"
// Use GNRNG for custom random generation
const rng = new Gnrng('my-seed')
const randomValue = rng.next() // 0.0 ~ 1.0
const randomInt = rng.nextRange(1, 100) // 1 ~ 99
rng.free() // Clean up WASM memoryBatch Operations (High Performance)
import { initWasm, createIdsBySeed, Gnrng, IdType } from '@nap5/gnrng-id'
await initWasm()
// Batch ID generation (much faster than individual calls)
const userIds = createIdsBySeed('user-batch', 1000, 8, IdType.User)
console.log(userIds.length) // 1000 unique user IDs
// Batch random number generation
const rng = new Gnrng('batch-seed')
const randomNumbers = rng.nextBatch(10000) // 10k numbers at once
const diceRolls = rng.nextRangeBatch(1, 6, 1000) // 1k dice rolls
rng.free()๐ API Reference
Initialization
initWasm(): Promise<void>
Initialize the WebAssembly module. Must be called before using any other functions.
await initWasm()Random Number Generation
class Gnrng
Deterministic random number generator.
const rng = new Gnrng('seed')
// Generate float [0.0, 1.0)
const value = rng.next()
// Generate integer [min, max)
const intValue = rng.nextRange(1, 100)
// ๐ Batch operations (high performance)
const batch = rng.nextBatch(1000) // 1000 floats
const rangeBatch = rng.nextRangeBatch(1, 10, 500) // 500 integers [1, 10)
// Clean up (important for memory management)
rng.free()gnrng(seed: string): Gnrng
Factory function to create Gnrng instance.
const rng = gnrng('my-seed')ID Generation
createIdBySeed(seed: string, size?: number, type?: IdType): string
Generate a deterministic ID based on seed.
createIdBySeed('my-seed') // "t_A7Bp9X2"
createIdBySeed('user-123', 8, IdType.User) // "u_K3mN9Pq5"๐ createIdsBySeed(baseSeed: string, count: number, size?: number, type?: IdType): string[]
Generate multiple deterministic IDs efficiently (batch operation).
createIdsBySeed('user-batch', 100, 8, IdType.User) // 100 unique user IDsTypes
IdType
Enum for ID prefixes:
enum IdType {
User = 'user', // Prefix: "u_"
Team = 'team', // Prefix: "tm_"
Project = 'project', // Prefix: "p_"
Default = 'default' // Prefix: "t_"
}โก Performance
TBD
- ๅๅฅใใใใใใๅฎ่กใฎๆนใๅบๆฌๆฉใ
- gnrngใฏใใใใตใคใบๅคงใใใปใฉๆๅฉใงๆฉใ
- createIdใฏใใใใตใคใบใๅฐใใ๏ผ100ๅใปใฉ๏ผใจNativeใฎๆนใๆฉใใใใใใตใคใบใๅคงใใ๏ผ1000ๅไปฅไธ๏ผใจwasmใฎๆนใๆฉใ
Performance Tips
โ
Use batch operations for processing many items
โ
Initialize WASM once at application startup
โ
Call rng.free() to avoid memory leaks
โ
Prefer deterministic IDs for reproducible results
๐ Examples
React Hook
import { useEffect, useState } from 'react'
import { initWasm, createId, IdType } from '@nap5/gnrng-id'
function useGnrngId() {
const [initialized, setInitialized] = useState(false)
useEffect(() => {
initWasm().then(() => setInitialized(true))
}, [])
const generateId = (size?: number, type?: IdType) => {
if (!initialized) throw new Error('WASM not initialized')
return createId(size, type)
}
return { initialized, generateId }
}Node.js Server
import express from 'express'
import { initWasm, createIdsBySeed, IdType } from '@nap5/gnrng-id'
const app = express()
// Initialize WASM on startup
await initWasm()
app.post('/api/users/batch', (req, res) => {
const { count = 100 } = req.body
// Generate batch of user IDs efficiently
const userIds = createIdsBySeed(
`batch-${Date.now()}`,
count,
8,
IdType.User
)
res.json({ userIds })
})Deno Application
import { serve } from 'https://deno.land/std/http/server.ts'
import { initWasm, Gnrng } from 'npm:@nap5/gnrng-id'
await initWasm()
serve((req) => {
const url = new URL(req.url)
if (url.pathname === '/random-batch') {
const rng = new Gnrng('server-seed')
const numbers = rng.nextBatch(1000)
rng.free()
return new Response(JSON.stringify({ numbers }))
}
return new Response('Not Found', { status: 404 })
})๐ Compatibility
Environments
- โ Node.js 18+
- โ Deno 1.40+
- โ Browsers with WASM support
- โ Bun (experimental)
Module Systems
- โ ESM (import/export)
- โ CommonJS (require)
- โ TypeScript
๐ ๏ธ Development
Prerequisites
- Rust 1.86.0+
- Node.js 22+
- wasm-pack
- pnpm 10+
Building
# Build WASM module
pnpm run build:wasm
# Build TypeScript library
pnpm run build:lib
# Build everything
pnpm run buildTesting
# Run tests
pnpm test
# Run benchmarks
pnpm run benchmark
# Generate coverage
pnpm run test:coverage๐ค Contributing
Contributions are welcome! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- wasm-bindgen for Rust-WASM bindings
- nanoid for alphabet inspiration
- Original GNRNG algorithm from gnrng
Made with โค๏ธ by Higashi Kota
๐ Give us a star โข ๐ Report Bug โข ๐ก Request Feature