[Solved] How to write a function that returns 2 if input is 1 and returns 1 if input is 2? [closed]


You can use binary XOR with 3 to do this

function returnTwo(input) {
    return input ^ 3;
}

Or as Phil suggested

function returnTwo(input) {
    return ~input + 4;
}

Or

function returnTwo(input) {
    return (input * 2) % 3;
}

Or

function returnTwo(input) {
    return Math.abs(input - 3);
}

Or

function returnTwo(input) {
    return input === 1 ? 2 : 1;
}

Or

function returnTwo(input) {
    return (input - 1) ? 1 : 2;
}

Or

function returnTwo(input) {
    return input * input === input ? 2 : 1;
}

— EDIT s4m0k

function returnTwo (input ) {
    return 3 - input;
}

6

solved How to write a function that returns 2 if input is 1 and returns 1 if input is 2? [closed]