Skip to content

Instantly share code, notes, and snippets.

@samoshkin
Created January 17, 2018 18:15
Show Gist options
  • Save samoshkin/d25273e2dfe96de8121e660390056887 to your computer and use it in GitHub Desktop.
Save samoshkin/d25273e2dfe96de8121e660390056887 to your computer and use it in GitHub Desktop.
ES6 replace default object-to-primitive conversion logic using Symbol.toPrimitive method
class Disk {
constructor(capacity){
this.capacity = capacity;
}
[Symbol.toPrimitive](hint){
switch (hint) {
case 'string':
return 'Capacity: ' + this.capacity + ' bytes';
case 'number':
// convert to KiB
return this.capacity / 1024;
default:
// assume numeric conversion as a default
return this.capacity / 1024;
}
}
}
// 1MiB disk
let disk = new Disk(1024 * 1024);
console.log(String(disk)) // Capacity: 1048576 bytes
console.log(disk + '') // '1024'
console.log(+disk); // 1024
console.log(disk > 1000); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment