Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Created July 30, 2020 20:18
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/3bf34b4371baf1cabc4f9c2e4260613c to your computer and use it in GitHub Desktop.
Save gladchinda/3bf34b4371baf1cabc4f9c2e4260613c to your computer and use it in GitHub Desktop.
// A function that can take amount and currency as arguments
// and returns a salary object.
function createSalaryObject(amount, currency = "USD") {
amount = Number(amount);
currency = String(currency).trim().toUpperCase();
currency = /^[A-Z]{3}$/.test(currency) ? currency : "USD";
return {
amount,
currency,
valueOf() { return amount },
toString() { return `${currency} ${amount}` }
};
}
// Create a new salary object
const salary = createSalaryObject(150000);
// Cast the salary object to a string (using String())
console.log(String(salary)); // "USD 150000"
// Cast the salary object to a string (using concatenation)
console.log("" + salary); // "150000"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment