Monday, 30 September 2013

Suggestions to improve JavaScript code to performance?

Suggestions to improve JavaScript code to performance?

I took a JavaScript challenge to finish a task related to logo of
"Breaking Bad" where letters in your first name and last name are spotted
with elements of periodic table and its respective atomic number. I wrote
the below code, any suggestions to improve performance or any best coding
practices
function Process() {
var ellist = {
"h": "1",
"he": "2",
"li": "3",
"be": "4",
"b": "5",
"c": "6",
.
.
.
"Lv":"116",
"Uus":"117",
"Uuo":"118"
};
var fname = document.getElementById("firstname");
var lname = document.getElementById("lastname");
var splits = fname.split("");
var value;
for (var i = 0; i < splits.length; i++) {
var onevalue = fname.indexOf(splits[i]);
var singlev = fname.substring(onevalue, onevalue + 1);
var doublev = fname.substring(onevalue, onevalue + 2);
var triplev = fname.substring(onevalue, onevalue + 3);
if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) {
value = splits[i];
if (ellist[doublev] || ellist[triplev]) {
value = ellist[doublev];
if (ellist[triplev]) {
value = ellist[triplev];
// some code here
}
// some code here
}
// some code here
}
}
Using the Process() function which contains the logic. The object ellist
contains the list of elements of periodic table with its atomic number.
First name is taken from textbox on webpage and stored in fname and
similarly the last name in lname and in the for loop it contains the code
which checks whether the firstname contains the string which matches the
elemetns of periodic table. Any suggestions?

No comments:

Post a Comment