0

I am converting c++ code into javascript that is here. The rest of the code looks fine but following function has a problem. First, second line inside while loop throws error Uncaught ReferenceError: Invalid left-hand side in assignment. When I change that to m = (A[m] >= key ? r : l); then this loop becomes infinite. How can I solve it in javascript?

    function CeilIndex(A, l, r, key) {
        var m;

        while( r - l > 1 ) {
            m = l + (r - l)/2;
            (A[m] >= key ? r : l) = m; // ternary expression returns an l-value
        }

        return r;
    }
0

3 Answers 3

1
if (A[m] >= key) {
    r = m;
} else {
    l = m;
}

JavaScript can't have variable lvalues except for properties (i.e. you could do obj[A[m] >= key ? 'r' : 'l'] = m, but not what you're proposing).

Sign up to request clarification or add additional context in comments.

Comments

1

You just need to break out your left-side properly. I don't know what you're trying to do, but assuming you're assigning m to either r or l:

if (A[m] >= key) {
    r = m;
} else {
    l = m;
}

Comments

1

In JavaScript you can do this instead:

A[m] >= key ? r = m : l = m;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.