Created
July 30, 2020 21:02
-
-
Save gladchinda/3acc394bc7ace7fc057f034a93da0c99 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function createSalaryObject(amount, currency = "USD") { | |
amount = Number(amount); | |
currency = String(currency).trim().toUpperCase(); | |
currency = /^[A-Z]{3}$/.test(currency) ? currency : "USD"; | |
// The string equivalent for amount (with currency) | |
const amountString = `${currency} ${amount}`; | |
return { | |
amount, | |
currency, | |
valueOf() { return amount }, | |
// Return `amountString` from `toString()` | |
toString() { return amountString }, | |
// Define a `[Symbol.toPrimitive]` method. | |
// Returns `amountString` for "default" hint. | |
[Symbol.toPrimitive](hint) { | |
return hint === "number" ? amount : amountString; | |
} | |
}; | |
} | |
// Create a new salary object | |
const salary = createSalaryObject(150000); | |
// Both String() function and string concatenation | |
// now yield the same result. | |
console.log(String(salary)); // "USD 150000" | |
console.log("" + salary); // "USD 150000" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment