Hey everyone,
I just submitted the code for Wherefore Art Thou challenge and, after a lot of thinking, I came up with two solutions to this problem and I want to share some thoughts with you guys.
WARNING: IF YOU DIDN’T PASS THE CHALLENGE JUST YET, LEAVE THIS POST
Ok. So the first solution I found was the least “elegant” code, but more intuitive to me. I used a filter() function, a for…in loop and some ternary operators in 10 lines of code. Here you have it:
function whatIsInAName ( collection , source ) {
return collection.filter( obj => {
let match = false;
for ( const sourceKey in source )
match = obj.hasOwnProperty( sourceKey )
&& source[sourceKey] == obj[sourceKey]
? true : false;
return match ? obj : null;
} );
}
Then I wanted to do it another way, to reduce the number of lines, to try more “functional programming” (map, reduce, etc), and to see it from another perspective. I used filter(), map() and reduce() functions in 7 lines after some time reading examples:
function whatIsInAName ( collection , source ) {
return collection.filter( obj => {
return Object.keys( source )
.map( key => obj.hasOwnProperty( key ) && source[ key ] === obj[ key ] )
.reduce( ( accum , currItem ) => accum && currItem );
} );
}
So far so good. BUT, I wanted to know how good they both performed in terms of speed, I found out that the first solution executes faster (actually way faster, more than half the time):
1st solution: 0.5 milliseconds.
2nd solution: 0.19999999999998863 milliseconds.
What do you think about this? Maybe I didn’t do enough tests? I’d like to know your opinion on the matter because, at least in this case, I find easier to read my first solution and it turns out to be also faster.
Happy coding!