views:

1037

answers:

2

These are the logical steps which I need to do with jquery:

x is a 2 digit number(integer) derived from an input.value();

If  var x is **not** 33 or 44
    Convert this 2 digit number to string;
    split the string in 2 parts as number;
    Add these 2 values until they reduce to single digit;
    Return var x value as this value;
Else
    Return var x value literally as 33 or 44 whatever is the case;

Thanks!

+1  A: 
if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        x = parseInt(parts[0]) + parseInt(parts[1]);
    }
    return x;
} else {
    return x;
}    

Works only if the input is really max 2 digits long as you say, else you'll need to add the numbers in a for loop over parts.length. E.g.:

if (x != 33 && x != 44) {
    while (x > 9) {
        var parts = ('' + x).split('');
        for (var x = 0, i = 0; i < parts.length; i++) {
            x += parseInt(parts[i]);
        }
    }
    return x;
} else {
    return x;
}    
BalusC
Thanks BalusC,I am getting a syntax error on line 8> return x;any idea why?
Richbyte
Maybe you forgot to put it in a `function`?
BalusC
+1  A: 

I'd try:

function process (x) {
    if ((x != 33) && (x != 44)) {
        while (x > 9) {
            x = Math.floor (x / 10) + (x % 10);
        }
    }
    return x;
}

I see little reason to convert it to a string when you can use arithmetic operations.

paxdiablo
You only forget to rename the two other `parts` after the copypaste :)
BalusC
Thanks BalusC,I am having trouble integrating this bit as a part of the parent jquery function. I would need to do this with jquery valriables :(.
Richbyte
you are right paxdiablo, i don't need to , was looking at the best way possible, thanks!
Richbyte
Uhm pax actually copypasted my question with a slight edit of the removal of the `else` part and renaming only `var parts` to `var digits` while not renaming the other two. I commented on that and then he updated his answer more using arithmetic operations and finally even downvoted my answer for no reason. Fair play :/ This one is truly better, I was just implementing your functional requirement literally. If pax wasn't playing unfair I would have upvoted this.
BalusC
@Balus, my original answer _was_ indeed a variation on yours, partly to placate the "we don't like multiple return points" crowd, partly to change the `if` statement since I prefer to avoid lots of negatives (although that's reverted since it turns out to be cleaner in my new answer) and partly to fix an error. So yes, it was copied from yours before my edits since that's easier than writing it from scratch. But my answer was most definitely _not_ just a copy of yours (and certainly isn't anything like yours now). In addition, I do _not_ downvote answers for no reason, that's not my style.
paxdiablo
I appreciate your help BalusC.
Richbyte
Richbyte
@pax: I take my words back.
BalusC