Skip to content

Commit

Permalink
refactor: safeMerge()
Browse files Browse the repository at this point in the history
  • Loading branch information
Andreas Richter committed Apr 6, 2020
1 parent 651472b commit 99a61da
Showing 1 changed file with 16 additions and 27 deletions.
43 changes: 16 additions & 27 deletions lib/safe-merge.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,34 +34,23 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

const merge = require('lodash/merge');

const map = require('lodash/map');
function safeMerge() {
const args = Array.from(arguments);
const data = merge({}, ...args.map(arg => arg.data));
const time = args.reduce(
(maxTime, arg) => ((arg.time || 0) > maxTime ? arg.time : maxTime),
0
);
const source = args.reduce((acc, arg) => {
if (arg.source) {
// NOTE: multiple source might not even exists. Tests contain only one source in each argument
Array.isArray(arg.source)
? (acc = [...acc, ...arg.source])
: acc.push(arg.source);
}
return acc;
}, []);

const max = require('lodash/max');

const reduce = require('lodash/reduce');

const filter = require('lodash/filter');

function toArray(value) {
if (Array.isArray(value)) {
return value;
}

if (value != null) {
return [value];
} else {
return [];
}
}

function sourceList(result, source) {
return toArray(result).concat(toArray(source));
}

function safeMerge(...args) {
const data = merge({}, ...Array.from(map(args, 'data')));
const time = max(filter(map(args, 'time')));
const source = reduce(map(args, 'source'), sourceList);
return {
data,
time,
Expand Down

0 comments on commit 99a61da

Please sign in to comment.