diff --git a/lib/factory.js b/lib/factory.js index bdc1288..5c8e345 100644 --- a/lib/factory.js +++ b/lib/factory.js @@ -456,52 +456,45 @@ Factory.prototype.getJobs = function getJobs() { * @returns The original job {} if duplicates found, false if not */ Factory.prototype.coalesceRequests = function coalesceRequests(res, context) { + var _this = this; + // Check for duplicate context in an array of jobs function checkIfDuplicate(jobs) { return _.find(jobs, {'context': context}); } - // Return an array of running jobs - function runningJobs(jobs) { - // Filters out pending or running jobs - function jobFilter(job) { - return job.status === constants.EVENTS.STATUS_PENDING || - job.status === constants.EVENTS.STATUS_RUNNING; - } + // Return an array of job that can be coalesced into + function coalescableJobs(jobs) { - var runningJobs = jobs.filter(jobFilter); - return runningJobs; - } - - // Return an array of jobs in the coalescing period - function coalescingJobs(jobs, coalescingPeriod) { - var coalescingJobs = []; + // Filters out pending, running, or finished jobs within the coalescing period + function jobFilter(job) { + if (job.status === constants.EVENTS.STATUS_PENDING || + job.status === constants.EVENTS.STATUS_RUNNING) { + return true; + } - for (var j = 0; j < jobs.length; j++) { - var otherJob = jobs[j]; - if(otherJob.endTime) { + if(job.endTime) { + var coalescingPeriod = _this.config.coalescingPeriod || 0; var now = Date.now(); - var diff = now - otherJob.endTime.getTime(); + var diff = now - job.endTime.getTime(); + if(diff <= coalescingPeriod) { - coalescingJobs.push(otherJob); + return true; } } + + return false; } - return coalescingJobs; + var filteredJobs = jobs.filter(jobFilter); + return filteredJobs; } // An array of job objects var jobs = this.getJobs(); - // If duplicate job is already running, attach responder to that job - var originalJob = checkIfDuplicate(runningJobs(jobs)); - if(originalJob) { - return originalJob; - } - - // If duplicate job has finished x minutes ago, return that job immediately - originalJob = checkIfDuplicate(coalescingJobs(jobs, this.config.coalescingPeriod)); + // If duplicate job, attach responder to that job + var originalJob = checkIfDuplicate(coalescableJobs(jobs)); if(originalJob) { return originalJob; }