0

in order to find an "intersection" of multiple users' settings (boolean), I need to compare their setting objects with each other. For example: if you click on a user, you see his settings and can edit them but if you select multiple users which can have different settings, I want to be able to show an indeterminate status in order to display that a specific setting is set to true for some users and to false for others. In case of multi select, the same settings will be applied to all selected users.

Here is an example of what I came up with so far and would like to know if there is a more elegant way to do it (as soon as there is at least two users with different settings, then I can ignore the rest): http://jsfiddle.net/kT7UP/

Thanks in advance.

1 Answer 1

2

You can make each property test into a common function where you pass in the property name. So all your repetitive for loops become this:

function checkCommonValue(prop) {
    for (var j = 0; j < userAll.length; j++) {
        if (userAll[j][prop] != model[prop]) {
            console.log('Indeterminate status');
            return(false);
        }
    }
    return(true);
}

checkCommonValue("Printing");
checkCommonValue("Sharing");
checkCommonValue("Reading");
checkCommonValue("AccountEnabled");
checkCommonValue("Fax");

Keep in mind the basic coding principle DRY (don't repeat yourself). If you find you're repeating code blocks that are almost the same, then it's time to think of a way to break that code down into common functions that you can call from multiple places rather than copy/paste the same code into multiple places.

2
  • Thanks a lot! I realized that I was repeating far too much but just couldn't think of your solution. This is extremely nice especially if you need to compare even more properties. Could you explain the paranthesis around false in your example please? I usually use "return true" without paranthesis and am curious what the difference is.
    – Bay
    Apr 25, 2012 at 21:20
  • In most cases, you do not need parens around the return value. There are a few cases (which escape me now, but I think it had to do with multiple statements or multiple line statements) where parens provide needed clarity to the interpreter. I have a habit of using them, but they are usually not required.
    – jfriend00
    Apr 25, 2012 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.