Sunday, March 4, 2018

.some in JavaScript

Alright, this has this example:

var array = [1, 2, 3, 4, 5];
 
var even = function(element) {
   return element % 2 === 0;
};
 
console.log(array.some(even));

 
 

What is above will spit true out to the console. I guess if there is one match of the condition it will return true and otherwise it will return false. What is more, and a little different, I was able to refactor the following TypeScript...

let matchedModel: SaveAnswerEventModel = null;
updateAnswerAction.model.forEach((saveAnswerEventModel) => {
   if (saveAnswerEventModel.question.id === answer.questionId) {
      matchedModel = saveAnswerEventModel;
   }
});

 
 

...into this:

let matchedModel: SaveAnswerEventModel = null;
updateAnswerAction.model.some((saveAnswerEventModel) => {
   if (saveAnswerEventModel.question.id === answer.questionId) {
      matchedModel = saveAnswerEventModel;
   }
   return true;
});

 
 

...is this a little less expensive? Does .some just fall out of looping when it finds a match? I don't know. In the last of the code snippets above we have to return true or false. We cannot return a more complicated type.

No comments:

Post a Comment