Click to See Complete Forum and Search --> : What does this function?


WillemW
February 20th, 2006, 12:44 PM
Hello people,

Yesterday I was visiting this site and I found an article about algorithms. On another site I found almost the same script but there's another function in it named "generate", this is the script:




function keyHandler(e) {
var target = e.target||e.srcElement;
var keyCode = e.which||e.keyCode;
if (target.nodeName == "INPUT" && target.name.length <= 3) {
if (keyCode > 46) { //Some control character
var character = String.fromCharCode(keyCode).toUpperCase();
target.value = character;
var num = parseInt(target.name.substr(1)) + 1;
var next = target.form.elements["c" + num];
if (next) next.focus();
} else {
var charCode = target.value.charCodeAt(0);
if (charCode < 30 ) target.select();
}
}
return true;
}

window.addListener("load", function() {
EventListener.invoke(document.forms[0]);
document.forms[0].addListener("keyup", keyHandler);
});


function missingLink(value) {
var code = value;
code = toHexCode(safeChars(code));
code = hexDoubleOdd(code);
code = addAll(code);
return code%16;
}

function generate(length) {
var code = "";
var toChar = new Array("B", "D", "F", "G", "J", "K", "L", "M", "P", "R", "S", "T", "V", "W", "X", "Z");
for (var i = 0; i < length-1; i++) {
code += toChar[Math.floor(Math.random() * 16)];
}
var remainder = missingLink(code);
return code + toChar[16-remainder];
}


My question is: what does this script exactly, and what happens by the function generate? I already know what the function missingLink(value) does with the code, but how about the other lines? I think it's something with an algorithm. I hope someone have an answer.

Kind regards,
WillemW.

PeejAvery
February 20th, 2006, 03:58 PM
...what does this script exactly, and what happens by the function generate? I already know what the function missingLink(value) does with the code, but how about the other lines? I think it's something with an algorithm. I hope someone have an answer.
Well, it randomly generates a letter from the array and then passes it to the missingLink() function. Since you already know what that does, you should be fine.

WillemW
February 21st, 2006, 02:29 PM
Ok but where in the function it will paste the generated letter?

PeejAvery
February 21st, 2006, 03:56 PM
Ok but where in the function it will paste the generated letter?
It returns what is generated. So you would have something like...

var retval = generate(16);
retval would return a 16 character whatever (I think hex).