Hi Theofanis, thanks for adding to the discussion. I totally agree that the last reducer is not needed and when it comes to performance, the for loop is always going to outperform the functional methods for large datasets. What is more interesting is the possibility to make it in one pass and that's where I believe your solution shines the most.
I even took a stab at that approach in one of my previous solutions, see code below.
functionsockMerchant(n,ar){let_colors={};letpairs=0;for(leti=0;i<n;i++){_colors[ar[i]]=(!!_colors[ar[i]])?_colors[ar[i]]+1:1;// do it in one passif((_colors[ar[i]]%2)==0)pairs+=1;}returnpairs;}constn=9;constsocks=[10,20,20,10,10,30,50,10,20];console.group('Sorted and counted');console.log(`There is a total of ${sockMerchant(n,socks)} pairs`);console.groupEnd();
The difference with yours ultimately is that your colors value can only be 1, 2 or 0 which I believe for the context of this exercise - just counting the pairs - is perfect.
The one above since it's keep adding to the total of stocked socks, needs to do a division by 2 anytime a new sock is added.
I will of course run all against the benchmark and since JS Perf is back up and running, I'll put them all there and make a public share of the results for documentation purpose.
Cheers
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi Theofanis, thanks for adding to the discussion. I totally agree that the last reducer is not needed and when it comes to performance, the for loop is always going to outperform the functional methods for large datasets. What is more interesting is the possibility to make it in one pass and that's where I believe your solution shines the most.
I even took a stab at that approach in one of my previous solutions, see code below.
The difference with yours ultimately is that your colors value can only be 1, 2 or 0 which I believe for the context of this exercise - just counting the pairs - is perfect.
The one above since it's keep adding to the total of stocked socks, needs to do a division by 2 anytime a new sock is added.
I will of course run all against the benchmark and since JS Perf is back up and running, I'll put them all there and make a public share of the results for documentation purpose.
Cheers