Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

string[index] doesn't work correctly #16

Closed
ngocdaothanh opened this issue Jun 17, 2018 · 4 comments
Closed

string[index] doesn't work correctly #16

ngocdaothanh opened this issue Jun 17, 2018 · 4 comments

Comments

@ngocdaothanh
Copy link

See the line console.log(string, i, char) below in the program to check if parentheses are balanced:

function check(string) {
  let count = 0

  for (let i = 0; i < string.length; i++) {
    const char = string[i]
    console.log(string, i, char)

    if (char === '(')
      count++
    else if (char === ')')
      count--

    console.log(count)
    if (count < 0) return false
  }

  return count === 0
}

console.log(check('()(()())'))

Expected output:

()(()()) 0 (
()(()()) 1 )
()(()()) 2 (
...

Actual output:

()(()()) 0 (
()(()()) 1 (
()(()()) 2 (
...

It seems that in this program string[index] always returns the first character.

@basicer
Copy link
Member

basicer commented Jun 17, 2018

The problem here is that ES6 block scoping isn't implemented yet, so the const applies to the whole function, and the assignment silently fails. Fixing #15 will make this more obvious.

@basicer basicer closed this as completed Jun 17, 2018
@ngocdaothanh
Copy link
Author

I think there's bug somewhere, because when the program is in ES5, it doesn't work as expected:

function check(string) {
  var count = 0

  for (var i = 0; i < string.length; i++) {
    var char = string[i]
    console.log(string, i, char)

    if (char === '(')
      count++
    else if (char === ')')
      count--

    if (count < 0) return false
  }

  return count === 0
}

console.log(check('()(()())'))

@basicer
Copy link
Member

basicer commented Jun 18, 2018

What is the expected output? I get:

Rambi:esper.js basicer$ node j.js 
()(()()) 0 (
()(()()) 1 )
()(()()) 2 (
()(()()) 3 (
()(()()) 4 )
()(()()) 5 (
()(()()) 6 )
()(()()) 7 )
true

@ngocdaothanh
Copy link
Author

I've just try running with the demo site again:
https://esper.js.org

The output looks good now. So it was because of the const problem as you explained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants