Created
July 30, 2018 22:41
-
-
Save gladchinda/ae9724ed88c04d22bbc79e62681fed98 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 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