-
-
Save chaitanyagupta/543519 to your computer and use it in GitHub Desktop.
var findItem = function(jid, items){ | |
for(var i = 0; i < items.length; ++i){ | |
var item = items[i]; | |
if(item.jid === jid){ | |
return item; | |
} | |
} | |
return null; | |
} |
var findItem = function(jid, items){ | |
var foundItem = null; | |
dojo.some(items, function(item){ | |
return (item.jid === jid) ? (foundItem = item, true) : false; | |
}); | |
return foundItem; | |
} |
//oh sorry that was a stupid typo, forgot a return. programming in ruby has made me forget to return :)
//is this better?
var findItem = function(items, jid) {
return items.filter(function(item) {return item.jid === jid})[0]
}
Yep, this works. Returns undefined instead of null (atleast in Chrome), but that's not a big deal.
Ruby doesn't need explicit returns? That's cool! Lisp doesn't need explicit returns either, that's where I made a lot of mistakes when I started working with javascript.
yeah ruby returns the last expression evaluated. return is used explicitly only in guard clauses :)
I just realized one issue with your snippet: it doesn't return as soon as it finds a match, rather it always goes through the entire array. The original snippets that I posted, on the other hand, quit as soon as they find a match.
Given this, can we do any better?
var arrayFind = function(items, predicate) {
for (int i=0; i<= itens.length; i++) {
if predicate(items[i], i) return items[i];
}
}
and then the rest is obvious
Haha, you've just implemented Common Lisp's some; I was wondering if there was a more concise solution apart from writing some in JS. If Javascript's Array.some behaved like this rather than returning just a boolean, it would have been so much more useful.
oh, yeah some is pretty neat in that it returns the value. I like that. Ruby's array.find does this, that's why I called it find. There is also an "any" which is meant to be used like some. Except you can rely on it even if your array contains false or nil ;-)
Won't work, that's where I tripped to initially. The
return
form will return from the inner function only, not from findItem.