DEV Community

Discussion on: 5 things I learnt during my latest Javascript Code Kata

Collapse
 
severo profile image
Sylvain Lesage

I really don't understand this part of code. Is something missing?

// sort edges by weight (min/max)
const asc = t === "min";
edges.sort(([edge_a, a], [edge_b, b]) => asc ? a - b : b - a);
Collapse
 
erikpischel profile image
Erik Pischel

Well, "t" is either "min" or "max". And edges is an array of 2 element arrays, e.g.

edge=[["AB",3], ["BC",9], ["AC",5]]

sort takes a function of two parameters that returns a number indicating whether the first parameter is smaller or bigger than the second parameter. The parameters are elements of the array. In our case these are 2 element arrays. In the code example, these are destructured as edge_a (e.g. "AB") and a (e.g. 3) respectively edge_b and b. The array edges is being sorted by the second element of the 2 element arrays.
Hope this helps.

Collapse
 
severo profile image
Sylvain Lesage • Edited

Ah OK. I didn't understand that t was a variable previously set to "min" or "max". Maybe it would be clearer to precise it, o add a line of code to show it.

Thanks for your article, btw.

Thread Thread
 
erikpischel profile image
Erik Pischel

I deleted the const because it doesn't contribute to the point I want to make. It's much clearer now. Thanks for your comment.