patternjavascriptMinor
More efficient version of an ID calculator in JavaScript
Viewed 0 times
versionjavascriptmoreefficientcalculator
Problem
The following function takes two numbers that are linked with a "user" and calculates an ID number based on that. I have been trying to make this as clean as possible, and would like some advice on how to make this more efficient. an example of the input would be "12195491" for the num and "3120" for the ts, which would output "8511"
function getidnumber(num, ts) {
num = num.substr(4, 4);
ts = ((ts == undefined) ? "3452" : (ts));
var _local5 = "";
var _local1 = 0;
while (_local1 < num.length) {
var _local4 = Number(num.substr(_local1, 1));
var _local3 = Number(ts.substr(_local1, 1));
var _local2 = String(_local4 + _local3);
_local5 = _local5 + _local2.substr(_local2.length - 1);
_local1++;
}
return("@user" + _local5);
};Solution
Here's a better implementation.
Used the unary
Used
Avoid performing a
Cached
Removed uneeded parenthesis.
Took advantage of the
Made sure that every variables were locally scoped. The
Used a single
Stole the % 10 idea from the other answer since I thought it was great ;)
Used the unary
+ operator for number conversion.Used
null instead of undefined since it's shorter and produces the same result because of type coersion.Avoid performing a
substring operation by starting to iterate from index 4.Cached
num.length into len so that we save on property lookups when the condition is evaluated for every loop iteration.Removed uneeded parenthesis.
Took advantage of the
+= operator.Made sure that every variables were locally scoped. The
_local1 variable in the selected answer isin't properly scoped.Used a single
var statement; it's a better practice to declare variables at the top of the function for readability.Stole the % 10 idea from the other answer since I thought it was great ;)
function getidnumber (num, ts) {
var i = 4,
len = num.length,
res = '@user';
ts = ts == null? '3452' : ts;
for (; i < len; i++) {
res += (+num[i] + +ts[i - 4]) % 10;
}
return res;
}Code Snippets
function getidnumber (num, ts) {
var i = 4,
len = num.length,
res = '@user';
ts = ts == null? '3452' : ts;
for (; i < len; i++) {
res += (+num[i] + +ts[i - 4]) % 10;
}
return res;
}Context
StackExchange Code Review Q#31607, answer score: 2
Revisions (0)
No revisions yet.