0
s = ['[', ']', '{', '}', '(', ')'];
copied = s;
console.log(copied.length);
var output;
for (i = 0; i < s.length; i++) {
  console.log('calling function', i);

  different();
}

function different() {
  if (copied[0] == '(' && copied[1] == ')') {
    copied.splice(0, 2);
    output = 'valid';
    console.log('checking', copied);
  } else if (copied[0] == '{' && copied[1] == '}') {
    copied.splice(0, 2);
    output = 'valid';
  } else if (copied[0] == '[' && copied[1] == ']') {
    copied.splice(0, 2);
    output = 'valid';
    console.log('checking', copied);
  } else {
    output = 'invalid';
  }
}

console.log(copied);
console.log(copied.length);
console.log('result is ', output);

i am getting the following output

6

calling function 0

checking [ '{', '}', '(', ')' ]

calling function 1

[ '(', ')' ]

2

result is valid

The problem is for loop runs only twice but it is supposed to run 6 times.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
suriyan
  • 35
  • 1
  • 2
  • 9

1 Answers1

0

Fixed a few issues with the code. The primary one being that the OP's different() function examines the same part of the array, no matter the state of the loop...

const s = ['[', ']', '{', '}', '(', ')', '[', '***']

for (i = 0; i < s.length - 1; i += 2) {
  let result = different(s[i], s[i + 1]);
  console.log(result)
}

function different(a, b) {
  let match =
    (a === '(' && b === ')') ||
    (a === '[' && b === ']') ||
    (a === '{' && b === '}')
  return `"${a}" and "${b}" ${match ? '' : 'do not'} match`
}

A more scalable approach would put represent the syntax in data, like this...

const s = ['[', ']', '{', '}', '(', ')', '[', '***']
const delimiters = {
  '[': ']',
  '(': ')',
  '{': '}',
}

for (i = 0; i < s.length - 1; i += 2) {
  let result = different(s[i], s[i + 1]);
  console.log(result)
}

function different(a, b) {
  let match = delimiters[a] === b;
  return `"${a}" and "${b}" ${match ? '' : 'do not'} match`
}
danh
  • 62,181
  • 10
  • 95
  • 136
  • Thanks @danh for your solution, it works – suriyan Dec 06 '21 at 16:51
  • You bet, @suriyan. Commenters were distracted by your choice of variable names. FYI, if `A` is a reference to an array or an object, `let B = A;` contrary to the comments, *really does make a copy of `A`*, but what the commenters are trying to say is that's a copy of the reference, *not the thing the reference refers to*. `B` and `A` are still both referring to the same thing. – danh Dec 06 '21 at 17:07
  • Hi @danh , yes i get it. The reason i wanted to have a copy of original array is i dont want to make any changes to the original array. – suriyan Dec 07 '21 at 12:45