n-base-integer
v1.1.2
Published
Arbitrary-base integer with custom charset, supporting addition, subtraction, multiplication, comparison, and common base conversion utilities.
Maintainers
Readme
n-base-integer
A TypeScript library for creating, converting, and performing arithmetic with integers in arbitrary bases (n-base), supporting custom charsets and large numbers.
For more awesome packages, check out my homepage💛
Features
- Arbitrary base support: Create integers in any base from 2 to 1,000,000
- Custom charsets: Support any character set, including emojis
- Large number handling: Beyond JavaScript's native number limits
- Complete arithmetic operations: Addition, subtraction, multiplication, division, modulo, and power
- Immutable and mutable operations: Choose between creating new instances or modifying in-place
- Base conversion: Convert between different bases efficiently
- Type-safe: Full TypeScript support with comprehensive type definitions
Installation
npm install n-base-integerQuick Start
import { NBaseInteger } from 'n-base-integer';
// Create from string (default base 10)
const a = NBaseInteger('12345');
// Create with specific base
const binary = NBaseInteger('1010', 2); // Binary
const hex = NBaseInteger('1A3F', 16); // Hexadecimal
// Create with custom charset
const custom = NBaseInteger('🔥💧🌍', 3, '🔥💧🌍');
// Since '🔥💧🌍' -> '012'
custom.toString(); // '💧🌍'
// Create from regular number
const fromNum = NBaseInteger.from(255, 16); // 255 in base 16
// Create from digit array [1,2,3] -> 123
const fromDigits = NBaseInteger.fromDigits([1, 2, 3], 10);API Reference
Factory Methods
NBaseInteger(str, base?, charset?)- Create from stringNBaseInteger.from(number, base)- Create from regular numberNBaseInteger.fromDigits(digits[], base, negative?)- Create from digit arrayNBaseInteger.defaultCharset- Get default charset ('0-9A-Za-z')NBaseInteger.setDefaultCharset(charset)- Set default charset
Properties
.base- The base of this number (readonly).isZero- True if the number is zero.isOdd/.isEven- Check parity.sgn- Sign of the number (-1, 0, or 1), same assgn(x)in math
Arithmetic Operations
Immutable operations (return new instance):
add(n: NBaseInteger | number)- Additionsub(n: NBaseInteger | number)- Subtractionmul(n: NBaseInteger | number)- Multiplicationdiv(n: NBaseInteger | number)- Division (quotient only)mod(n: NBaseInteger | number)- Modulo (remainder only)divmod(n: NBaseInteger | number)- Division with remainder{ quotient, remainder }pow(exponent: NBaseInteger | number)- Exponentiation
Mutable operations (modify in place):
addAssign(n: NBaseInteger | number)- AdditionsubAssign(n: NBaseInteger | number)- SubtractionmulAssign(n: NBaseInteger | number)- MultiplicationdivAssign(n: NBaseInteger | number)- DivisionmodAssign(n: NBaseInteger | number)- Moduloinc()- Increment by 1dec()- Decrement by 1
const a = NBaseInteger('100');
const b = NBaseInteger('7');
// Immutable operations
const sum = a.add(b); // 107
const product = a.mul(3); // 300
const { quotient, remainder } = a.divmod(b); // 14 remainder 2
// Mutable operations
a.addAssign(b); // a becomes 107
a.inc(); // a becomes 108Comparison Operations
cmp(n)- Comparethiston, return (-1, 0, 1)eq(n)/ne(n)- Equal / not equalgt(n)/gte(n)- Greater than / greater than or equallt(n)/lte(n)- Less than / less than or equal- Absolute comparisons:
cmpAbs(n),eqAbs(n),gtAbs(n), etc.
if (a.gt(b)) {
console.log('a is greater than b');
}
console.log(a.cmp(b)); // -1, 0, or 1Sign Operations
negate()- Get-this(immutable)negateAssign()- Setthisto-thisabs()- Get absolute value (immutable)absAssign()- Absolute value in placesetSign(sgn: -1 | 0 | 1)- Set sign to -1, 0, or 1zero()- Set to zero
const n = NBaseInteger('-42');
const positive = n.abs(); // 42
n.negateAssign(); // n becomes 42
n.setSign(-1); // n becomes -42Base Conversion
convertTo(base)- Convert to another basetoBinary()- Convert to binary (base 2)toOctal()- Convert to octal (base 8)toDecimal()- Convert to decimal (base 10)toHex()- Convert to hexadecimal (base 16)
const decimal = NBaseInteger('255');
const binary = decimal.toBinary(); // '11111111' in base 2
const hex = decimal.toHex(); // 'FF' in base 16
const base36 = decimal.convertTo(36); // '73' in base 36Other Methods
toString(charset?: string | null)- Convert to string representation.charsetdefault value is '0...9A...Za...z'(can be set viaNBaseInteger.setDefaultCharset()).- note that
charsetcan be omitted but not explicitly beundefined
- note that
- When
charsetisnull, just return the digits separated with comma. - When
charsetisstring, use it to stringify every digit after check.
toNumber()- Convert to JavaScript number (throws if >Number.MAX_SAFE_INTEGER)toBigInt()- Convert to JavaScript BigIntclone()- Create a copy
const n = NBaseInteger('1010', 2);
console.log(n.toString()); // '1010'
console.log(n.toString(null)); // '0,1,0,1' (digit array)
console.log(n.toNumber()); // 10
console.log(n.toBigInt()); // 10n
// Custom charset for output
const custom = NBaseInteger('255').convertTo(3);
console.log(custom.toString('ABC')); // Uses A=0, B=1, C=2Advanced Usage
Custom Character Sets:
// Emoji base-3 number system
const emojiNum = NBaseInteger('🔥💧🌍', 3, '🔥💧🌍');
console.log(emojiNum.toDecimal().toString()); // Converts to decimal
// Base-64 with custom charset
const base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const b64num = NBaseInteger('Hello', 64, base64);Large Number Support:
// Numbers beyond JavaScript's safe integer limit
const huge = NBaseInteger('999999999999999999999999999999');
const result = huge.mul(huge); // Still works perfectly
console.log(result.toString()); // Exact result, no precision lossBase Conversion Chain:
const original = NBaseInteger('777', 8); // Octal
const decimal = original.toDecimal(); // Convert to decimal
const binary = decimal.toBinary(); // Then to binary
const hex = binary.toHex(); // Finally to hexPerformance Notes
- Operations are optimized for efficiency with large numbers
- Base conversions use efficient algorithms for arbitrary precision
- In-place operations (
*Assignmethods) create less objects when you don't need immutability - Caching is used internally for frequently accessed
maxIntandcharsets
License
MIT
