0o
A JavaScript octal number parser.
Node.js's support for ECMAScript 2015(ES6) octal literals(0o)
| 4.3.2 and above | 0.12.16 | 0.10.47 and below |
|---|---|---|
| Supported | Supported(with harmony flag) | Unsupported |
But require("0o") works on all the versions of Node.js & web browsers! XD
Features
- Works well on both web browsers and Node.js
- Works in strict mode
- No dependency
- Standard JavaScript with high compatibility
- Does not ignore the sign of
-0 - You can make it accepts
NaNand infinite values if you want
require("0o") vs parseInt(..., 8) & require("octal")
require("0o"); it's very clear, and WTF-less.
| require("0o")(true) | require("0o")() | parseInt(..., 8) and require("octal") | |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| -0 | -0 | -0 | 0 |
| -10 | -8 | -8 | -8 |
| Infinity | InvalidArgumentError | Infinity | NaN |
| -Infinity | InvalidArgumentError | -Infinity | NaN |
| NaN | InvalidArgumentError | NaN | NaN |
| -NaN | InvalidArgumentError | NaN | NaN |
| 9 | InvalidArgumentError | InvalidArgumentError | NaN |
| "0+10" | InvalidArgumentError | InvalidArgumentError | 0 |
| "-00010" | -8 | -8 | -8 |
| "\n\n+10 \n\r\t" | 8 | 8 | 8 |
| "LOL" | InvalidArgumentError | InvalidArgumentError | NaN |
| "\n\t\r -Infinity \n" | InvalidArgumentError | -Infinity | NaN |
| undefined | InvalidArgumentError | InvalidArgumentError | NaN |
| "" | InvalidArgumentError | InvalidArgumentError | NaN |
| "+9" | InvalidArgumentError | InvalidArgumentError | NaN |
Example
var Oo = require("0o")(true);
// If `notational` is true, NaN and infinite values are not allowed;
// otherwise, they are allowed.
console.log("+0o0 is mathematically equivalent to ", Oo(+0)); // 0
console.log("-0o0 is mathematically equivalent to ", Oo(-0)); // -0
console.log("parseInt(0, 8)?", parseInt(0, 8)); // 0
console.log("parseInt(-0, 8)?", parseInt(-0, 8)); // 0
try
{
Oo("9"); // throws an InvalidArgumentError.
}
catch(error)
{
// error.name === "InvalidArgumentError"
console.error(error.name, error.message);
}