Я работаю над проектом стажировки, который, хотя он и не сфокусирован на производительности, хотел бы быть настолько быстрым (и скудным), насколько это возможно.Пока у меня есть одна рабочая версия (с ошибкой) и одна концепция вышеупомянутой функции:
V1 (BUG: не удается обработать числа с точками и запятыми.)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
// Alternative: isNaN(nStr) ? throw new Error(`${nStr} is NaN`) : nStr += ``;
nStr += ``;
// If the input is of the form 'xxxx.yyy', split it into x1 = 'xxxx'
// and x2 = '.yyy'.
let x = nStr.split(`.`);
let x1 = x[0];
let x2 = x.length > 1 ? `.` + x[1] : ``;
let rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
// x1 takes the form 'x,xxx' - no matter how long the number,
// this is where the commas are added after every three digits.
x1 = x1.replace(rgx, `$1` + `,` + `$2`);
}
return x1 + x2;
}
V2 Concept (выглядит медленнее, но ошибок нет)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
nStr += ``;
// Remove any potential dots and commas.
nStr = nStr.replace(`.`, ``);
nStr = nStr.replace(`,`, ``);
// Split the number into an array of digits using String.prototype.split().
// Iterate digits. After every three, add a comma.
// Transform back into a string.
return nStr;
}