Skip to content

Instantly share code, notes, and snippets.

@basekays
Created October 20, 2016 02:48
Show Gist options
  • Select an option

  • Save basekays/ea58ce1ec1edc84d517a38f86909f732 to your computer and use it in GitHub Desktop.

Select an option

Save basekays/ea58ce1ec1edc84d517a38f86909f732 to your computer and use it in GitHub Desktop.
var _ = {};
_.find = function(list, condition) {
var resultArray = [];
for (var i = 0; i<list.length; i++) {
if (condition(list[i])) {
resultArray.push(list[i]);
}
}
if (resultArray.length) {
return resultArray[0];
}
return undefined;
}
@amy-chiu

amy-chiu commented Oct 30, 2016

Copy link
Copy Markdown

so i think is more complicated than it needs to be. if a value passes the truth test, return out immediately... if there isn't one that passes the truth test in that list, then you return undefined...so think about the first part of how _.find works, specifically "return out immediately" if you find a value that passes the truth test. you could simply write it like this then:


_.find = function(list, condition) {
  for (var i = 0; i<list.length; i++) {
    if (condition(list[i])) {
      return list[i];
    }
  }
  return undefined;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment