/*
Program: Print numbers with a thousand separator as spaces in JavaScript.
Architecture notes:
-------------------
- JavaScript's Intl.NumberFormat allows customizing:
* useGrouping → true
* grouping separator → via locale or custom replacement
- JavaScript does not directly allow setting a custom thousands separator,
but we can:
1. Format using a locale that uses commas.
2. Replace commas with spaces.
This is efficient and avoids manual digit processing.
Performance notes:
------------------
- Formatting is O(n) in the number of digits.
- Intl.NumberFormat is optimized in JS engines.
- Memory usage is minimal; only small strings are created.
Pitfalls:
---------
- Intl.NumberFormat does not allow custom separators directly.
- Floats may introduce rounding; this example focuses on integers.
- Very large integers (BigInt) require special handling.
Security notes:
---------------
- No external input parsing; safe for demonstration.
- Avoid printing sensitive values in real systems.
Tests:
------
- Positive numbers
- Negative numbers
- Zero
- Very large integers
*/
// Format a number using spaces as thousand separators
function formatWithSpaces(value) {
try {
// Format using US locale (comma separators), then replace commas with spaces
const formatted = new Intl.NumberFormat("en-US", {
useGrouping: true,
maximumFractionDigits: 0
}).format(value);
return formatted.replace(/,/g, " ");
} catch (err) {
return `unformatted (error: ${err.message})`;
}
}
// Test cases
const tests = [
0,
42,
1234,
987_654_321,
-1_234_567,
1_000_000_000_000_000_000n // BigInt example
];
console.log("Running test cases:\n");
for (const n of tests) {
console.log("Original: " + n);
console.log("Formatted: " + formatWithSpaces(n));
console.log();
}
/*
run:
Running test cases:
Original: 0
Formatted: 0
Original: 42
Formatted: 42
Original: 1234
Formatted: 1 234
Original: 987654321
Formatted: 987 654 321
Original: -1234567
Formatted: -1 234 567
Original: 1000000000000000000
Formatted: 1 000 000 000 000 000 000
*/