💾n.toHex()
to binary / octal / hex format.
// ⭐ getter/setter
Object.defineProperties(Number.prototype, {
// n.binary
binary: {
get() { return this.toString(2) },
},
// n.octal
octal: {
get() { return this.toString(8) },
},
// n.hex
hex: {
get() { return this.toString(16).toUpperCase() },
},
});
// ⭐ general function
function formatFunc(pre, base) {
return function format({
prefix = false,
pad = { length: 0, char: '0' },
} = {}) {
// ⭐ `pad` might be overridden, better destructure again
const { length = 0, char = '0' } = pad;
return (prefix ? pre : '') +
this.toString(base).padStart(length, char).toUpperCase();
}
}
// num.toBinary()
Number.prototype.toBinary = formatFunc('0b', 2);
// num.toOctal()
Number.prototype.toOctal = formatFunc('0o', 8);
// num.toHex()
Number.prototype.toHex = formatFunc('0x', 16);
// export nothing
module.exports = {};Last updated