Skip to content

Commit

Permalink
feat: custom step for js translator
Browse files Browse the repository at this point in the history
  • Loading branch information
davinov committed Aug 28, 2020
1 parent 026ac18 commit ba7389f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/lib/translators/js.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,19 @@ export class JavaScriptTranslator extends BaseTranslator {
return data.map(addTextColumnToRow);
};
}

/**
* Transform a "custom" step into corresponding function
*
* The "query" parameter of the custom step should be a javascript function, of which the first parameter will be
* the data table, and the second an object of all available domains.
*/
custom(step: Readonly<S.CustomStep>) {
const func = Function('"use strict";return (' + step.query + ')')();
return function(data: Readonly<DataTable>, dataDomains: Readonly<DataDomains>) {
return func(data, dataDomains);
};
}
}

/**
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/js.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,23 @@ describe('Pipeline to js function translator', () => {
]);
});
});

describe('custom step', () => {
it('should apply the custom function to data', () => {
const addPlipPloupAndDoubleValue = jsTranslator.custom({
name: 'custom',
query: `function transformData(data) {
return data.map(d => ({
...d,
value: d.value * 2,
plip: "ploup"
}));
}`,
});
expect(addPlipPloupAndDoubleValue(SAMPLE_DATA.domainA, {})).toEqual([
{ label: 'A', value: 2, plip: 'ploup' },
{ label: 'B', value: 4, plip: 'ploup' },
]);
});
});
});

0 comments on commit ba7389f

Please sign in to comment.