From e77a27662be9debc69eb83e89ec762282a75c159 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Thu, 11 Aug 2016 20:11:27 -0400 Subject: [PATCH] lib function to interleave trace updates into a restyle --- src/lib/index.js | 39 ++++++++++++++++++++++++++++++++++ test/jasmine/tests/lib_test.js | 28 ++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/lib/index.js b/src/lib/index.js index e2b0a6f8f95..a6354d5b407 100644 --- a/src/lib/index.js +++ b/src/lib/index.js @@ -616,3 +616,42 @@ lib.numSeparate = function(value, separators) { return x1 + x2; }; + +/** + * Interleaves separate trace updates (frames) into a restyle command. + * Attributes not specified in both traces are set to `undefined` so that + * they are not altered by restyle. Object paths are *not* expanded. + * + * @example + * lib.interleaveTraceUpdates([{x: [1]}, {x: [2]}]) + * // returns {x: [[1], [2]]} + * + * @param {array} traces the trace updates to be interleaved + * + * @return {object} an object contianing the interleaved properties + */ +lib.interleaveTraceUpdates = function(traces) { + var i, j, k, prop, trace, props; + var n = traces.length; + var output = {}; + + for(i = 0; i < traces.length; i++) { + trace = traces[i]; + props = Object.keys(trace); + for(j = 0; j < props.length; j++) { + prop = props[j]; + if(!output[prop]) { + // If not present, allocate a new array: + output[prop] = []; + + // Explicitly fill this array with undefined: + for(k = 0; k < n; k++) { + output[prop][k] = undefined; + } + } + output[prop][i] = traces[i][prop]; + } + } + + return output; +}; diff --git a/test/jasmine/tests/lib_test.js b/test/jasmine/tests/lib_test.js index 76d0dff5b1e..8e995c754b6 100644 --- a/test/jasmine/tests/lib_test.js +++ b/test/jasmine/tests/lib_test.js @@ -1334,6 +1334,34 @@ describe('Test lib.js:', function() { }).toThrowError('Separator string required for formatting!'); }); }); + + describe('interleaveTraceUpdates', function() { + it('wraps property updates in arrays', function() { + var input = [{x: [1], 'marker.color': 'red'}]; + var output = Lib.interleaveTraceUpdates(input); + + expect(output).toEqual({ + x: [[1]], + 'marker.color': ['red'] + }); + }); + + it('merges traces into a single restyle', function() { + var input = [ + {x: [1], 'marker.color': 'red'}, + {y: [[7, 8], [4, 2]], 'marker.goodness': 'very', symbols: {visible: 'please'}} + ]; + var output = Lib.interleaveTraceUpdates(input); + + expect(output).toEqual({ + x: [[1], undefined], + y: [undefined, [[7, 8], [4, 2]]], + 'marker.color': ['red', undefined], + 'marker.goodness': [undefined, 'very'], + 'symbols': [undefined, {visible: 'please'}] + }); + }); + }); }); describe('Queue', function() {