Highly Optimised version of encode and decode available as npm package here
https://www.npmjs.com/package/digipinindia
String Building Optimization:
Before: Used array .push() and .join() which creates intermediate arrays
After: Direct string concatenation with capacity hinting
Impact: Eliminates array allocation and join operation overhead
Mathematical Optimizations:
Before: Division by 4 using /GRID_SIZE
After: Multiplication by 0.25 (faster than division)
Before: Repeated Math.min(3, Math.max(0, value)) calls
After: Simplified conditional logic
Impact: ~15-20% faster arithmetic operations
Loop Unrolling:
Before: HYPHEN_POSITIONS.has(level + 1) Set lookup
After: Direct comparison level === 2 || level === 5
Impact: Eliminates Set lookup overhead
Hyphen Removal Optimization:
Before: Regex .replace(/-/g, '')
After: Simple character-by-character loop
Impact: Avoids regex engine overhead
Precision Rounding:
Memory Optimizations 💾
Eliminated Intermediate Arrays: Removed array creation in encoding function
Reduced Object Allocations: Fewer temporary objects created during processing
Removed Unused Constants: Eliminated HYPHEN_POSITIONS Set
Pre-calculated Values: Store gridSizeReciprocal = 0.25 to avoid repeated calculations
Highly Optimised version of encode and decode available as npm package here
https://www.npmjs.com/package/digipinindia
String Building Optimization:
Before: Used array .push() and .join() which creates intermediate arrays
After: Direct string concatenation with capacity hinting
Impact: Eliminates array allocation and join operation overhead
Mathematical Optimizations:
Before: Division by 4 using /GRID_SIZE
After: Multiplication by 0.25 (faster than division)
Before: Repeated Math.min(3, Math.max(0, value)) calls
After: Simplified conditional logic
Impact: ~15-20% faster arithmetic operations
Loop Unrolling:
Before: HYPHEN_POSITIONS.has(level + 1) Set lookup
After: Direct comparison level === 2 || level === 5
Impact: Eliminates Set lookup overhead
Hyphen Removal Optimization:
Before: Regex .replace(/-/g, '')
After: Simple character-by-character loop
Impact: Avoids regex engine overhead
Precision Rounding:
Memory Optimizations 💾
Eliminated Intermediate Arrays: Removed array creation in encoding function
Reduced Object Allocations: Fewer temporary objects created during processing
Removed Unused Constants: Eliminated HYPHEN_POSITIONS Set
Pre-calculated Values: Store gridSizeReciprocal = 0.25 to avoid repeated calculations