Skip to content

Instantly share code, notes, and snippets.

@AppWerft
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AppWerft/74c4c675f6191dfd0fc4 to your computer and use it in GitHub Desktop.
Save AppWerft/74c4c675f6191dfd0fc4 to your computer and use it in GitHub Desktop.
Array.prototype.contains
Array.prototype.contains = function(k, callback) {
var self = this;
return (function check(i) {
if (i >= self.length) {
return callback(false);
}
if (self[i].id === k.id) {
return callback(true);
}
return process.nextTick(check.bind(null, i+1));
}(0));
}
@greelgorke
Copy link

// this is an asynchronous and recursive contains method
// it checks if a given element k is in the array (by comparing the id properties), and calls the provided callback with the result which is true or false

Array.prototype.contains = function(k, callback) {
  //save the this
  var self = this;
  //return the result of this iife. actually the return value doesn't matter at all, since the callback takes the result, the return keyword could be omited here. the i parameter is the index of the current element in the array
  return (function check(i) {
    // if i is bigger or equal the length of the actual array (self), then we are done and found nothing (the end-clause for recursion)
    if (i >= self.length) {
      // the return statement here makes the following code readable, because you don't need the else branch
      return callback(false);
    }
   // if we are not through the array, compare the id property of the k with the id of the current element in the array call the callback with true, if they are equal
    if (self[i].id === k.id) {
           // the return statement here makes the following code readable, because you don't need the else branch
      return callback(true);
    }
   // if you are here, call yourself again with a higher index. process.nextTick makes this call also async, so the stack can unwind and the eventloop can proceed, bind provides the array index +1 to the next call of this funtion (its partially applied from this moment.)
    return process.nextTick(check.bind(null, i+1));
  // call the iife and start with the index 0 of the array
  }(0));
}

@greelgorke
Copy link

easy, right? 😸

@AppWerft
Copy link
Author

Yes it is. The code avoids a deadlock.

@AppWerft
Copy link
Author

But – "process.nextTick":what it is? A new JS command?

@AppWerft
Copy link
Author

@greelgorke
Copy link

you could also use setTimeout

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