Skip to content

Instantly share code, notes, and snippets.

@crissdev
Created May 17, 2021 17:49
Show Gist options
  • Save crissdev/b77f3d0ddd6edcdab7cfa37d377d8ae1 to your computer and use it in GitHub Desktop.
Save crissdev/b77f3d0ddd6edcdab7cfa37d377d8ae1 to your computer and use it in GitHub Desktop.
Using Symbol.toPrimitive and toJSON method for better code
class Byte {
#value
constructor(value = 0) {
this.#value = value
}
toJSON() {
return this.#value
}
[Symbol.toPrimitive](hint) {
if (hint === 'number')
return this.#value
else
return this.#format(this.#value)
}
#format(value) {
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
if (value == 0) return '0 B'
var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)))
return Math.round(value / Math.pow(1024, i), 2) + ' ' + sizes[i]
}
}
const value = new Byte(102_400)
console.log(+value) // 102400
console.log(`${value}`) // 100 KB
console.log(value < 102_500) // true
console.log(value > 102_500) // false
console.log(JSON.stringify(value)) // 102400
console.log([
new Byte(300),
new Byte(14_250_000),
new Byte(10_000),
new Byte(200)
].sort((f, s) => f - s).join(' | '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment