简体   繁体   中英

Javascript return and ternary operator with var, possible?

I'm sorry if this question is a duplicate, but I really don't know how to search for it. This question may sound "odd" for an expert JavaScript programmer, but I'm not.

I'm basically trying to do a "one line return", without wasting another line of code. I know that it's not good, and the following it's not code for production:

var _ = require('underscore');

module.exports = function (digits) {
    if (!/^\d+$/.test(digits)) return undefined;

    var precomp = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];

    var sum = _.reduce(digits.toString(), function (mem, dgt, idx) {
        return mem + (idx % 2 == 0 ? parseInt(dgt) : precomp[dgt]);
    }, 0);

    return (var mod = sum % 10 == 0) ? 0 : 10 - mod; // Error
};

The last line throws an error because the var keyword. I remember doing sometimes the same in PHP.

EDIT : I don't think so "hard" to read the question before answer... I'm asking if it's possible, I'm not saying it's right, good looking, or whatever.

(By the way this is the luhn check calculation)

VariableDeclaration are not expressions. Just declare it before.

module.exports = function (digits) {
    var mod;

    // ...

    return (mod = sum % 10 ...
}

I think the only way for you to do this is:

var mod = sum % 10;
return (mod == 0) ? 0 : 10 - mod;

Who cares about one extra line of code? Why does that matter?

I think you're trying too hard here. Just move var mod before the return statement. You're NOT going to be struck dead by the software gods for having one more line of code here. Clarity over conciseness.

JavaScript is not PHP

var mod = sum % 10;
return (mod === 0) ? 0 : 10 - mod;

I see you don't like any of the answers so far. One way to avoid declaring the variable first is this, which you probably won't like either:

return (sum % 10 == 0) ? 0 : 10 - (sum % 10);

This doesn't require an extra line, but it does require an extra mod.


Another option, which might make the code extemely confusing, is to add a dummy argument to the function:

module.exports = function (digits, mod) {
    /* code */
    return (mod = sum % 10) == 0 ? 0 : 10 - mod; // Error
};

Since you don't use sum for any other purpose, you could move the % operator up, doing:

var _ = require('underscore');

module.exports = function (digits) {
    if (!/^\d+$/.test(digits)) return undefined;

    var precomp = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];

    var sum = _.reduce(digits.toString(), function (mem, dgt, idx) {
        return mem + (idx % 2 == 0 ? parseInt(dgt) : precomp[dgt]);
    }, 0) % 10;

    return (sum == 0) ? 0 : 10 - sum; // Error
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM