I have created a game that is based on a grid being populated with words
In my code I have a small bit of underscore.js that helps my words fit in the space available in the grid without breaching the grids barriers.
I understand that it is very powerful java script and don’t personally have a problem with it. But my team manager would like to get rid of it for some jQuery that will provide the same solution as there is only one function and would save me having a whole library. How I would replace this with some jQuery?
function getWordToFitIn(spaceAvail, wordlist) {
var foundIndex = -1;
var answer = _.find(wordlist, function (word, index) {
if (word.length <= spaceAvail) {
foundIndex = index;
return true;
}
});
if (foundIndex == -1) {
answer = getXSpaces(spaceAvail);
_.find(wordlist, function (word, index) {
if (word[0] == " ") {
foundIndex = index;
return true;
}
});
}
if (foundIndex != -1) {
wordlist.splice(foundIndex, 1);
}
return answer;
}
As far as I can see, the only underscore method youre using is
_.find. But I don’t think you are using it as it was intended. It looks like you are simply looping and returning true when a criteria is met.You can use the native
forEachif you don’t have legacy support, or use a shim. Or you can use thejQuery.eachmethod.The first loop could probably (I’m not 100% sure about the
answervariable) be written like this:And the second one: