Answer to Challenge #399 from https://www.reddit.com/r/dailyprogrammer/
// add up all letters in a string, with 'a' being 1 and 'z' being 26. Other characters have value 0.
// we will elect to change uppercase to lowercase to make this solution a little more flexible.
var aVal = 'a'.charCodeAt(0);
function letterVal(s){
if(s >= "a" && s <= "z") return s.charCodeAt(0) - aVal;
else if(s >= "A" && s <= "Z") return s.toLowerCase().charCodeAt(0) - aVal;
else return -1;
}
function evaluate(str){
var o = 0;
for(var xint = 0, len = str.length;xint < len;xint++)
o += letterVal(str.charAt(xint)) + 1;
return o;
}
For example, evaluate('a') would return 1, evaluate('b') would return 2, and evaluate('5') would return 0.
No comments:
Post a Comment