Convert an alphabetic string into digits and recursively sum them so they're below a certain max
For a game like http://gangstaname.com/names/pirate
by andfinally
HTML
<div id="output"></div>
JavaScript
var nouns = [
"Nitwit",
"Cretin",
"Village Idiot",
"Elf",
"Pebble-Eater",
"Lip-Trembler",
"Jelly Chaser",
"Inpatient",
"Adult",
"Pole Dancer",
"Helot",
"Hedonist",
"Arachnophobe",
"Halfwit",
"Blockhead",
"Brute",
"Animalcule",
"Beast",
"Chump",
"Pudding"
];
// Convert alpha chars to numerical equivalents
function str2num (mystr) {
mystr = mystr.toUpperCase();
var conv = [],
l = mystr.length,
regex = /^[A-Za-z]+$/;
for (var i = 0; i < l; i++) {
if (regex.test(mystr.charAt(i))) {
conv.push(mystr.charCodeAt(i) - 64);
}
}
var c = conv.length,
sum = 0;
for (var j = 0; j < c; j++) {
sum += conv[j];
}
return sumDigits(sum);
}
// Recursively add digits of number together
// till the total is less than length of word lists
function sumDigits (number) {
console.log('Starting number: ' + number);
var listLength = nouns.length;
var sum = number % listLength;
if (number > listLength) {
var remainder = Math.floor(number / 10);
sum += sumDigits(remainder);
console.log('Sum = ' + sum);
}
if (sum > listLength) {
console.log('Sum is greater than ' + listLength);
sum = sumDigits(sum);
}
console.log('Sum = ' + sum);
return sum;
}
$(document).ready(function(){
$('#output').html(nouns[ str2num('John Smith') ]);
});