Flatten css classes args

Benchmark created on


Setup

const args = ['class1', 'class2', 'class3 class4', 'class5, class6', 'class7', 'class 8,class9'];

Test runner

Ready to run.

Testing in
TestOps/sec
split and filter
let flatArray = [];

if(!Array.isArray(args)) {
	args = [args];
} else if(Array.isArray(args[0])) {
	args = args[0];
}

for(let i = 0; i < args.length; i++) {
	const parts = args[i].split(/[\s,]+/);

	for(let j = 0; j < parts.length; j++) {
		flatArray.push(parts[j]);
	}
}

return flatArray.filter(Boolean);
ready
complex loop
let flatArray = [];

if (typeof args === 'string') {
	args = [args];
} else if (Array.isArray(args[0])) {
	args = args[0];
} else {
	return flatArray;
}

for (let i = 0; i < args.length; i++) {
	const str = args[i];
	if (typeof str !== 'string') continue;

	let start = 0, len = str.length;
	for (let j = 0; j <= len; j++) {
		const c = str[j];
		if (c === ' ' || c === ',' || j === len) {
			if (j > start) {
				flatArray.push(str.slice(start, j));
			}
			start = j + 1;
		}
	}
}

return flatArray;
ready
flatMap, split and filter
if (typeof args === 'string') {
	args = [args];
} else if (Array.isArray(args) && Array.isArray(args[0])) {
		args = args[0];
	}

	return (args || [])
		.flatMap(str =>
			typeof str === 'string'
				? str.trim().split(/[\s,]+/)
				: []
		)
		.filter(Boolean);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.