You can create your own mapping function if jQuery does not resolve it.
var stoppableMap = function (inputArray, mainFunction, haltFunction) {
var result = [];
for (var i = 0; i < inputArray.length; i++) {
if (haltFunction(result, inputArray[i], i) === false) {
break;
}
result.push(mainFunction(inputArray[i], i));
}
return result;
}
What happens here is this: you call the above function by passing a vector as input and a function that receives index and element, similarly to what you would do with the function $.map.
.
For each vector element, the function passed as the mainFunction
parameter will be executed once. the first parameter it receives is the current element, and the second parameter is the index of the current element.
The difference is in the function passed as the third parameter, haltFunction
. It is also executed for each element of the original vector, but before mainFunction
. It receives three parameters: the resultant vector of the mapping so far, the current element and the index of the current element. If it returns false
(explicit - ""
, 0
, null
and undefined
do not work), the mapping function loop is interrupted. CQD.
You can modify the function at will: make the stop function run after and not before the main function, pass one more parameter to have more context or whatever else your logic needs.
Note that this function is much simpler than $.map
. It does not iterate over objects or flatten vectors every round of the main function you pass. You can implement these details if necessary.
Use example, which for when it finds an element of value 3
:
stoppableMap([1, 2, 3, 4, "a Maria é um barato"],
function (elem) {
return "elemento de valor " + elem;
},
function (accumulate, elem) {
if (elem == 3) return false;
});
Good luck;)