The flatMap operator is commonly defined as map followed by flatten. This module uses flatten(a).map(f)
where it should instead be flatten(a.map(f))
.
After making this change I get faster results for flatmapjs (using node v6.9.2):
$ node test.js
// => flatMapFast took: 1548.439797 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
// => flatMapConcatApply took: 1426.5782669999999 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
// => flatMapConcatRest took: 1620.313789 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
// => flatmapjs took: 624.206646 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
'use strict';
const arrNum = [1, 2, 3];
const flatten = (a) => a.reduce((x, y) => x.concat(y));
const flatMapFast = (a, f) => flatten(a.map(f));
const flatMapConcatApply = (a, f) => Array.prototype.concat.apply([], a.map(f));
// Note that this version requires the `--harmony` flag.
const flatMapConcatRest = (a, f) => [].concat(...a.map(f));
/* https://www.npmjs.com/package/flatmap v0.0.3 */
const flatmapjs = function (arr, iter, context) {
var results = [];
if (!Array.isArray(arr)) return results;
arr.forEach(function (value, index, list) {
var res = iter.call(context, value, index, list);
if (Array.isArray(res)) {
results.push.apply(results, res);
} else if (res != null) {
results.push(res);
}
});
return results;
};
const testPerf = require('testperf');
const fn = (i) => [i, i + i];
testPerf("flatMapFast", flatMapFast, arrNum, fn);
console.log(flatMapFast(arrNum, fn));
testPerf("flatMapConcatApply", flatMapConcatApply, arrNum, fn);
console.log(flatMapConcatApply(arrNum, fn));
// Note that this version requires the `--harmony` flag.
testPerf("flatMapConcatRest", flatMapConcatRest, arrNum, fn);
console.log(flatMapConcatRest(arrNum, fn));
testPerf("flatmapjs", flatmapjs, arrNum, fn);
console.log(flatmapjs(arrNum, fn));
Looking just at flatten, it seems (a) => Array.prototype.concat.apply([], a)
is fastest.
$ node flatten.js
// => flattenReduce took: 749.408898 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
// => flattenConcatApply took: 641.470689 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
// => flattenConcatRest took: 944.365671 milliseconds.
[ 1, 2, 2, 4, 3, 6 ]
'use strict';
const arrNum = [[1,2], [2,4], [3,6]];
const flattenReduce = (a) => a.reduce((x, y) => x.concat(y));
const flattenConcatApply = (a) => Array.prototype.concat.apply([], a);
// Note that this version requires the `--harmony` flag.
const flattenConcatRest = (a) => [].concat(...a);
const testPerf = require('testperf');
testPerf("flattenReduce", flattenReduce, arrNum);
console.log(flattenReduce(arrNum));
testPerf("flattenConcatApply", flattenConcatApply, arrNum);
console.log(flattenConcatApply(arrNum));
// Note that this version requires the `--harmony` flag.
testPerf("flattenConcatRest", flattenConcatRest, arrNum);
console.log(flattenConcatRest(arrNum));