diff --git a/packages/analytics/src/segment.js b/packages/analytics/src/segment.js index fd249c1ea..41f5615ac 100644 --- a/packages/analytics/src/segment.js +++ b/packages/analytics/src/segment.js @@ -80,6 +80,7 @@ import core from './core'; * @name segment * @param {String} [path=value] path * @param {Boolean} [aggregate=true] aggregate all values for all paths (or not) + * @param {Boolean} [identifier=false] path to use to set value result field (if not set or not exists, 1 is use as a default value) * @returns {Object} */ export default function segment(data, feed) { @@ -88,6 +89,7 @@ export default function segment(data, feed) { return; } const aggr = this.getParam('aggregate', true); + const idt = this.getParam('identifier', false); const path = this.getParam('path', 'value'); const fields = Array.isArray(path) ? path : [path]; @@ -98,19 +100,20 @@ export default function segment(data, feed) { .map((item) => (Array.isArray(item) ? item : [item])); const values = valuesOrig[0] && Array.isArray(valuesOrig[0][0]) ? flatten(valuesOrig) : valuesOrig; + const weight = idt === false ? 1 : get(data, idt, 1); if (aggr) { values.reduce((pre, cur) => pre.concat(cur), []) .reduce((pre, cur) => { if (pre) { - feed.write(core([pre, cur], 1)); + feed.write(core([pre, cur], weight)); } return cur; }, false); } else { values.map((item) => item.reduce((pre, cur) => { if (pre) { - feed.write(core([pre, cur], 1)); + feed.write(core([pre, cur], weight)); } return cur; }, false)); diff --git a/packages/analytics/test/network.js b/packages/analytics/test/network.js index 1b4a36fca..d81633708 100644 --- a/packages/analytics/test/network.js +++ b/packages/analytics/test/network.js @@ -30,6 +30,62 @@ describe('network', () => { }); }); + it('segment #3', (done) => { + ezs.use(statements); + const res = []; + from([ + { + id: 'doc#1', + value: [ + 1, + 2, + 3, + 4, + ], + }, + { + id: 'doc#2', + value: [ + 4, + 5, + 6, + ], + }, + { + id: 'doc#3', + value: 6, + valueBis: 7, + }, + { + id: 'doc#4', + value: [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + ], + }, + ]) + .pipe(ezs('segment', { path: ['value', 'valueBis'], identifier: 'id' })) + .pipe(ezs('reducing')) + .on('data', (chunk) => { + assert(typeof chunk === 'object'); + res.push(chunk); + }) + .on('end', () => { + assert.equal(6, res.length); + assert.equal(1, res[0].id[0]); + assert.equal(2, res[0].id[1]); + assert.equal(2, res[0].value.length); + assert.equal(2, res[5].value.length); + done(); + }); + }); + + it('segment #1', (done) => { ezs.use(statements); const res = [];