fast-cartesian
Version:
Fast cartesian product
105 lines (38 loc) • 961 B
JavaScript
import{validateInputs}from"./validate.js";
const fastCartesian=(
inputs)=>
{
validateInputs(inputs);
const result=[];
if(inputs.length===0){
return result
}
const loopFunc=getLoopFunc(inputs.length);
loopFunc(inputs,result);
return result
};
export default fastCartesian;
const getLoopFunc=(length)=>{
const cachedLoopFunc=cache[length];
if(cachedLoopFunc!==undefined){
return cachedLoopFunc
}
const loopFunc=mGetLoopFunc(length);
cache[length]=loopFunc;
return loopFunc
};
const cache={};
const mGetLoopFunc=(length)=>{
const indexes=Array.from({length},getIndex);
const start=indexes.
map((index)=>`for (const value${index} of arrays[${index}]) {`).
join("\n");
const middle=indexes.map((index)=>`value${index}`).join(", ");
const end="}\n".repeat(length);
return new Function(
"arrays",
"result",
`${start}\nresult.push([${middle}])\n${end}`
)
};
const getIndex=(value,index)=>String(index);