Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compacting arrays in JavaScript

What is JavaScript equivalent to Ruby's Array#compact?

Long version.... I followed the examples at blog.nemikor.com. His last example closes out old requests, but then pendings continues to be filled with obsolete requests. This looks like a memory leak to me.

My solution is to iterate over pendings with filter as below, but this seems like there may be a race condition between pendings.push and pendings = pendings.filter. Am I being paranoid? If a race condition exists, how should I fix it?

var pendings = [];

// there is a route
app.get('/some/path', function (request, response) {
  pendings.push({
    response: response,
    requestedAt: new Date().getTime()
  });
});

setInterval(function () {
  var expiration = new Date().getTime() - (1000 * 30);
  pendings = pendings.filter(function (pending, index) {
    if (pending.requestedAt > expiration) {
      return true;
    } else {
      pending.response.writeHead(408, { 'Content-Type': 'text/plain' });
      pending.response.end('');
    }
  });
}, 1000);
like image 252
ravinggenius Avatar asked May 30 '11 23:05

ravinggenius


People also ask

What is compact array?

() : compact! () is a Array class method which returns the array after removing all the 'nil' value elements (if any) from the array. If there are no nil values in the array it returns back the nil value.

What does compact do JavaScript?

compact() function is an inbuilt function in Underscore. js library of JavaScript which is used to return an array after removing all the false values. The false values in JavaScript are NaN, undefined, false, 0, null or an empty string.

Does JavaScript reduce modify array?

The reduce() method does not change the original array.


1 Answers

You have no threads in JavaScript, so there can be no race condition. All code is sequenced and will transfer control only after it's done running. So your interval function will run till completion before any other function is going to touch pendings.

This holds for things like setTimeout and setInterval.

As an experiment: If you made a timeout using setTimeout to fire after 1 second. And after that you write a while-loop that blocks for 2 seconds, your timeout will fire after that, so much longer than 1 second.

Something crude:

var timer = setTimeout(function () {
    alert("hi!");
}, 1000);
var now = new Date();
var till = new Date(now + 2);
while(new Date() < till) {}   // block for 2 seconds
like image 111
Halcyon Avatar answered Sep 30 '22 08:09

Halcyon