blob: 7d7e584d4c95b54ef6fd5ec6775d2fb154c97e04 [file] [log] [blame]
<!DOCTYPE html>
<!--
Copyright (c) 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/base/base.html">
<link rel="import" href="/base/iteration_helpers.html">
<script>
'use strict';
/**
* @fileoverview Provides event merging functionality for grouping/analysis.
*/
tv.exportTo('tv.e.audits', function() {
function mergeEvents(inEvents, mergeThreshold, mergeFunction,
opt_startFunction, opt_endFunction) {
var startFunction = opt_startFunction;
var endFunction = opt_endFunction;
if (!startFunction)
startFunction = function(event) { return event.start; };
if (!endFunction)
endFunction = function(event) { return event.end; };
var remainingEvents = inEvents.slice();
remainingEvents.sort(function(x, y) {
return startFunction(x) - startFunction(y);
});
if (remainingEvents.length <= 1) {
var merged = [];
if (remainingEvents.length == 1) {
merged.push(mergeFunction(remainingEvents));
}
return merged;
}
var mergedEvents = [];
var currentMergeBuffer = [];
var rightEdge;
function beginMerging() {
currentMergeBuffer.push(remainingEvents[0]);
remainingEvents.splice(0, 1);
rightEdge = endFunction(currentMergeBuffer[0]);
}
function flushCurrentMergeBuffer() {
if (currentMergeBuffer.length == 0)
return;
mergedEvents.push(mergeFunction(currentMergeBuffer));
currentMergeBuffer = [];
// Refill merge buffer if needed.
if (remainingEvents.length != 0)
beginMerging();
}
beginMerging();
while (remainingEvents.length) {
var currentEvent = remainingEvents[0];
var distanceFromRightEdge = startFunction(currentEvent) - rightEdge;
if (distanceFromRightEdge < mergeThreshold) {
rightEdge = Math.max(rightEdge, endFunction(currentEvent));
remainingEvents.splice(0, 1);
currentMergeBuffer.push(currentEvent);
continue;
}
// Too big a gap.
flushCurrentMergeBuffer();
}
flushCurrentMergeBuffer();
return mergedEvents;
}
return {
mergeEvents: mergeEvents
};
});
</script>