1

So recently I was doing a node school challenge, Here's the task:

Return a function that takes a list of valid users, and returns a function that returns true if all of the supplied users exist in the original list of users.

Here's the solution:

   module.exports = function (goodUsers) {
   return function (submittedUsers) {
       return submittedUsers.every(function (submittedUser) {
           return goodUsers.some(function (goodUser) {
               return goodUser.id === submittedUser.id;
           });
       });
   };
};

Basically its a function that takes in an object of ids and compares it with another one. it returns true if if the second objects' ids are in the first object. Here's an example: http://s8.postimg.org/ql8df5iat/Screen_Shot_2014_02_01_at_5_32_07_PM.png

However I've read the MDN examples for awhile and just can't seem to understand why this solution works! Can someone walk me through step by step on what's actually happening here? Why does this work? How do the every() and some() methods handle the differences is array length? etc

-Thanks

1
  • 1
    The function returns true if for every submittedUser there is at least one goodUser with the same id. Commented Feb 2, 2014 at 1:44

1 Answer 1

2

Actually the functions every and some don’t care about array length.

every will just execute an arbitrary code for each element of your first array.

some will just return true if there is at least one object with the same id' in the second array.

Note === this will "short circuit" in the case of null or undefined values.

Hope this helps.

Personally, I prefer the double “for” loop syntax as I think it is more readable.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you it makes a lot more sense now! I agree with the loops but I was practicing functional programming :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.