Created
May 9, 2024 07:21
-
-
Save gioragutt/65fe6dd2d44ea1b0603c89e541723a91 to your computer and use it in GitHub Desktop.
Paramutations - parameter permutation utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type VariadicTupleOfVariadicTuples = readonly [...(readonly [...(readonly unknown[])])]; | |
type ProductResult<T extends VariadicTupleOfVariadicTuples> = { | |
// @ts-expect-error should be good | |
[K in keyof T]: T[K][number]; | |
}; | |
function product<T extends VariadicTupleOfVariadicTuples>(arrays: T): ProductResult<T> { | |
return arrays.reduce( | |
(prevAccumulator: any[][], currentArray: any[]) => { | |
const newAccumulator: any[][] = []; | |
prevAccumulator.forEach(prevAccumulatorArray => { | |
currentArray.forEach(currentValue => { | |
newAccumulator.push(prevAccumulatorArray.concat(currentValue)); | |
}); | |
}); | |
return newAccumulator; | |
}, | |
[[]], | |
) as ProductResult<T>; | |
} | |
export type ParamValues<T extends Record<string, unknown>> = { | |
[K in keyof T]: T[K][]; | |
}; | |
export const paramutations = <T extends Record<string, unknown>>(matrix: ParamValues<T>): T[] => { | |
const inputToProduct = Object.values(matrix); | |
const keys = Object.keys(matrix); | |
const permutations = product(inputToProduct); | |
return permutations.map(permutations => { | |
return Object.fromEntries(keys.map((k, i) => [k, permutations[i]])) as T; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment