I found on some online coding exercises and this one looks really cool and I wanted to give it a shot.
Problem Statement
Quinn is a pretty popul
My attempt to understand
var persons = input.split(/\s+/).slice(1).reduce(function(obj,name,i,names){
return (obj[name] = (obj[name] || []).concat([names[i%2 ? i-1 : i+1]]), obj);
},{});
First input.split(/\s+/).slice(1)
Gives us an array with all of the names in it.
Now
(obj[name] = (obj[name] || []).concat([names[i%2 ? i-1 : i+1]]), obj);
obj is set by default to due to {}
according to the reduce method property.
name is current value which is basically going from Alden
all the way to Ally
. i
will go from 1-10
and names
is the array
Now we are saying set obj[name] = obj[name].concat([names[i%2 ? i-1 : i+1]]),obj);
IF this is possible. If this isn't possible set obj[name] = [].concat([names[i%2 ? i-1 : i+1]]),obj);
. This is my interpretation from reading up on ||
Example iteration
first obj = {}
, and name will be Alden
so the type Alden i.e persons = { Alden: ..}
will be obj[Alden].concat(names[2],obj)
, it will be 2, since 1 mod 2 doesn't get reached.
Now there is where I am a bit confused... what exactly is the ,obj
doing here..? am I interpreting this right?