I was looking over the cash register guide because I got stuck on how to convert the input array of cid (cash in drawer) into an object. However, after looking at the guide one part that I don’t fully understand what it’s doing is the part where it’s using the reduce() method to convert the cid to an object.
Could someone help walk me through exactly what this code is doing?
Just to clarify the parts I do understand, I understand that the new object is called register, and that the object is being created by performing the reduce method on the cid input. I’m not sure on this, but I believe that since a second function is being used within the reduce method, that this second function is taking the denomination and quantity of each value from the sub-arrays of the cid array. acc.total += curr is creating a new related object key value where acc is the denomination in the cid sub-array and curr is the value attached to it in cid, but now converted to a key index pair in our register object… but acc[curr] = curr – I have no clue what role this plays in creating the new object. This solution seems really elegant, but it’s possible I’m completely misunderstanding it all together…
Here is the complete guide for reference where I got this code snippet:
As you know cid is 2d array. where curr is holding the name of the denom and curr is holding its value. So the within the reduce function acc acts as a temp object within the function. where acc.total stores the total value of all the denom present in the drawer and now the second part
This line of code keeps adding denom to the object which are done adding to the total and evaluates as acc.[curr = PENNY]= [curr= 1.01].
It’s going to take me a minute to fully interalize all of this. I didn’t know you could create temporary arguments as objects that have not been defined outside of the function. That’s a totally wild concept to me. Thanks for taking the time to respond! I think if I spend a little time playing with this I can implement it. (also, that’s a nice code execution tool you linked, thx for sharing)