0.1.4 โ€ข Published 5 months ago

@nap5/gnrng-id v0.1.4

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

@nap5/gnrng-id

npm version License: MIT

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-id

JSR (for Deno)

deno add npm:@nap5/gnrng-id

Browser (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 memory

Batch 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 IDs

Types

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 build

Testing

# 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.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments


Made with โค๏ธ by Higashi Kota

๐ŸŒŸ Give us a star โ€ข ๐Ÿ› Report Bug โ€ข ๐Ÿ’ก Request Feature

0.1.4

5 months ago

0.1.3

5 months ago

0.1.2

5 months ago

0.1.1

5 months ago