Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Created July 30, 2020 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladchinda/3acc394bc7ace7fc057f034a93da0c99 to your computer and use it in GitHub Desktop.
Save gladchinda/3acc394bc7ace7fc057f034a93da0c99 to your computer and use it in GitHub Desktop.
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