So this code is a function that takes a string (referred to as “code”) as its argument and returns a computed checksum (as a number).
But all this is is a function definition. You must use the function. You do that by calling the function with an appropriate argument. For example:
luhn_checksum('4111111111111111')
(This returns the value 0
.)
You will note that I took the sample credit card number and wrapped it in single quotes to make it into a string (as expected by the function). If you send this function a number, it will not work. (Though we could easily modify the function to accept a number and just turn that number into a string internally.)
Now, another thing to note about this function (as written) is that it expects our string to be free of any whitespace. If we pass it a string that includes whitespace it will break. For example:
luhn_checksum('4111 1111 1111 1111')
returns NaN
(“not a number”).
This function would be a lot easier to work with if we just make it so it accepts numbers or strings and also strips out any whitespace. We can accomplish this with just one line (line 3 below):
function luhn_checksum(code) {
// convert argument to string and remove all whitespace:
code = String(code).replace(/\s/g, '');
var len = code.length;
var parity = len % 2;
var sum = 0;
for (var i = len - 1; i >= 0; i--) {
var d = parseInt(code.charAt(i));
if (i % 2 == parity) {
d *= 2;
}
if (d > 9) {
d -= 9;
}
sum += d;
}
return sum % 10;
}
Note: I don’t actually write my own JavaScript code using the semicolon, it’s just that I’m using VS Code at the moment and I have a prettier installed that inserts that crap for me.
Anyway, now that you have this function, how do you use it?
Well, you just call the function and in that function call is where you insert your Bubble dynamic value (not in the function definition):
luhn_checksum(Construct-Your-Bubble-Dynamic-Expression-Here)
Because of the changes we made to the function, that dynamic value can either be a string (what Bubble calls a text) or a number. Looks to me like you’re using an Input set to type number, so you’re good to go.
Your final code block that you put in Run JavaScript will look something like this:
function luhn_checksum(code) {
// convert argument to string and remove all whitespace:
code = String(code).replace(/\s/g, '');
var len = code.length;
var parity = len % 2;
var sum = 0;
for (var i = len - 1; i >= 0; i--) {
var d = parseInt(code.charAt(i));
if (i % 2 == parity) {
d *= 2;
}
if (d > 9) {
d -= 9;
}
sum += d;
}
return sum % 10;
}
luhn_checksum(Input A - number's value)