Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Created July 30, 2018 22:41
Show Gist options
  • Select an option

  • Save gladchinda/ae9724ed88c04d22bbc79e62681fed98 to your computer and use it in GitHub Desktop.

Select an option

Save gladchinda/ae9724ed88c04d22bbc79e62681fed98 to your computer and use it in GitHub Desktop.
function pricing(literals, ...replacements) {
// Initialize the final string
let finalString = '';
for (let i = 0; i < replacements.length; i++) {
// Get the current literal and replacement
const literal = literals[i];
const replacement = replacements[i];
// Trim trailing whitespaces from the current literal
const trimmed = literal.trimRight();
const length = trimmed.length;
// Check if current replacement is a number
const isNumber = typeof replacement === 'number';
// Check if current literal string ends with $
const isPrice = /\$$/.test(trimmed);
// Check if number is followed by literal that ends with $
// and use the desired formatting
finalString += (isNumber && isPrice)
? `${trimmed.substr(0, length - 1).trimRight()} USD ${replacement.toFixed(2)}`
: `${literal}${replacement}`;
}
// Attach the last literal to the final string
return finalString + literals[literals.length - 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment