0

I'm writing a quick sort function in Javascript to sort an array of objects like this (sort by the Num property):

let Pairs = [
   { ID: 'C', Num: 21 },
   { ID: 'B', Num: 45 },
   { ID: 'F', Num: 0 },
   { ID: 'E', Num: 1 },
   { ID: 'D', Num: 9 },
   { ID: 'A', Num: 100 }
];

But I found out that adding semicolons in my function partition() solved the bug in my prorgam, without the semicolons behind the swapPair() function, my program gave out the same array as input. Here is my code:

const swapPair = (a, b) => {
   let t = a;
   a = b;
   b = t;
   return [a, b]
}
function partition(a, left, right, pivotIndex) {
   pivotValue = a[pivotIndex].Num;
   // Move Pivot to the End
   [a[pivotIndex].ID, a[right].ID] = swapPair(a[pivotIndex].ID, a[right].ID);// This Semicolon
   [a[pivotIndex].Num, a[right].Num] = swapPair(a[pivotIndex].Num, a[right].Num);// This Semicolon
   storeIndex = left;
   for (let i = left; i <= right - 1; i++) {
      if (a[i].Num <= pivotValue) {
         [a[storeIndex].ID, a[i].ID] = swapPair(a[storeIndex].ID, a[i].ID);// This Semicolon
         [a[storeIndex].Num, a[i].Num] = swapPair(a[storeIndex].Num, a[i].Num);// This Semicolon
         storeIndex = storeIndex + 1
      }
   }
   // Move Pivot to the right place
   [a[storeIndex].ID, a[right].ID] = swapPair(a[storeIndex].ID, a[right].ID);// This Semicolon
   [a[storeIndex].Num, a[right].Num] = swapPair(a[storeIndex].Num, a[right].Num);// This Semicolon
   return storeIndex
}

I guess the problem is the way I use destructing assignment? But I couldn't figure out the cause, Please help me out:).


UPDATE:

The problem is in deed destructing assignment, My function returns an array so this problem is pretty hard to notice:

function foo(){
  ...
  return [a,b,c]
}

[A,B,C]=foo()
[D,E,F]=foo()

but without the semicolon, the code will be interperted as:

[A,B,C]=[x,y,z]
[D,E,F]=[m,n,p]
=>
[A,B,C]=[x,y,z][D,E,F]=[m,n,p]
=>
[A,B,C]=[x,y,z][F]=[m,n,p]
=>
[A,B,C]=[m,n,p]

Thank you Felix Kling.

  • 1
    See https://stackoverflow.com/q/68934612/218196 which I just answered a couple of days ago (but is a bit more specific than the duplicate). – Felix Kling Sep 01 '21 at 06:54
  • You can write javascript without semicolon, you only need to insert them if you start a line with a parenthesis `(` or a bracket `[`. https://stackoverflow.com/a/16421633/9942418 – Alexandre Elshobokshy Sep 01 '21 at 06:56

0 Answers0