Created
January 17, 2018 18:15
-
-
Save samoshkin/d25273e2dfe96de8121e660390056887 to your computer and use it in GitHub Desktop.
ES6 replace default object-to-primitive conversion logic using Symbol.toPrimitive method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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