Last active
March 4, 2019 07:36
-
-
Save behnamazimi/e3a2d57419d2699e1300f097c018e01e to your computer and use it in GitHub Desktop.
Pay Attention on Comments
This file contains 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
// Comments in your code. | |
// Dirty Code | |
function priceFormatter(price, separator = '/') { | |
if (price == null) // return when price is null | |
return '' | |
let tmp_price = [], | |
tmp_c = 1; // initial variables | |
price = price.toString(); // convert price to string | |
// lopp on price chars | |
for (let i = price.length - 1; i >= 0; i--) { | |
tmp_price.push(price[i]); // push price[i] to result array | |
if (tmp_c === 3 && i > 0) { | |
tmp_price.push(separator); // push separator on each 3 char | |
tmp_c = 0; // set counter to zero | |
} | |
tmp_c++; // add counter | |
} | |
// return a string | |
return tmp_price.reverse().join(''); | |
} | |
// Clean Code | |
/** | |
* This function get a [string] number and separate triple with separator char. | |
* | |
* @param {number} price | |
* @param {string} separator '/' as default separator | |
* @return {string} | |
*/ | |
export default function priceFormatter(price, separator = '/') { | |
if (price == null) | |
return '' | |
let tmp_price = [], | |
tmp_c = 1; | |
price = price.toString(); // convert int or any other types to string | |
// this loop will return a reversed array of chars | |
for (let i = price.length - 1; i >= 0; i--) { | |
tmp_price.push(price[i]); | |
if (tmp_c === 3 && i > 0) { | |
tmp_price.push(separator); // push separator on each 3 char | |
tmp_c = 0; | |
} | |
tmp_c++; | |
} | |
// re reverse and join the chars array of formatting and return string | |
return tmp_price.reverse().join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment