Code Snippet Series: Remove Junk from Array
Functional Javascript
Posted on August 2, 2020
Quiz
There are two key areas to increase the performance of this code without losing robustness; can you spot them?
/**
@func
remove junk (non-value-based data) from an arr
@param {*[]} a
@return {*[]}
*/
export const removeNonVals = a => a.filter(v => {
return v !== null && v !== undefined
&& !(v.constructor === String && v.trim() === "")
&& !(v.constructor === Object && Object.keys(v).length === 0)
&& !(Array.isArray(v) && v.length === 0)
});
//@tests
//@fixtureData
const aDirty = [
"Casbah", "abcd",
"", "p",
"", "255",
undefined, null,
"", " ",
[], {}, "[]", "{}"
[[]],
[["nested"]],
NaN, Infinity, 0, -0,
5, -1, 1e30, BigInt(3145),
n => n
, , , , ,
];
const aClean = removeNonVals(aDirty);
console.log(aClean);
/*
@output
[
'Casbah', 'abcd',
'p', '255',
'Warsaw', '1855',
'[]', [ [ 'nested' ] ],
NaN, Infinity,
0, -0,
5, -1,
1e+30, 3145n,
[Function (anonymous)]
]
*/
//@perftest
timeInLoop("removeNonVals", 1e6, () => removeNonVals(aDirty))
/*
removeNonVals: 1e+6: 2.601s
*/
TimeInLoop Source Code
https://gist.github.com/funfunction/91b5876a5f562e1e352aed0fcabc3858
💖 💪 🙅 🚩
Functional Javascript
Posted on August 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.