Skip to content

Instantly share code, notes, and snippets.

@romgrk
Created August 18, 2024 22:08
Show Gist options
  • Save romgrk/79b735a9b662b8f8b4c1c0c6ca0afc6a to your computer and use it in GitHub Desktop.
Save romgrk/79b735a9b662b8f8b4c1c0c6ca0afc6a to your computer and use it in GitHub Desktop.
import b from 'benny';
import { input, theme } from './data'
function slowMatch(objects: typeof input) {
const variants = theme.variants
const result = []
for (let i = 0; i < objects.length; i++) {
const props = objects[i] as any
const styles = []
variantLoop: for (let i = 0; i < variants.length; i += 1) {
const variant = variants[i];
const variantProps = variant.props as any;
for (const key in variantProps) {
if (props[key] !== variantProps[key] && props.ownerState?.[key] !== variantProps[key]) {
continue variantLoop;
}
}
styles.push(variant.style);
}
result.push(styles)
}
return result
}
const interestProps =
Array.from(
new Set(theme.variants.flatMap(v => Object.keys(v.props)))
)
const e = (v: any) => {
// XXX: undefined, functions, objects
return JSON.stringify(v)
}
theme.variants.forEach(v => {
const matches = eval(`(function matches(props, ownerState) {
return (${Object.entries(v.props).map(([key, value]) =>
`(props[${e(key)}] === ${e(value)} || ownerState[${e(key)}] === ${e(value)})`
).join(' && ')})
})`);
(v as any).matches = matches
})
function fastMatch(objects: typeof input) {
const variants = theme.variants
const result = []
for (let i = 0; i < objects.length; i++) {
const props = objects[i] as any
const styles = []
for (let i = 0; i < variants.length; i += 1) {
const variant = variants[i];
if (!(variant as any).matches(props, props.ownerState ?? {})) {
continue
}
styles.push(variant.style);
}
result.push(styles)
}
return result
}
console.log(slowMatch(input))
console.log(fastMatch(input))
b.suite(
'Benchmark playground',
b.add('slowMatch', () => {
slowMatch(input)
}),
b.add('fastMatch()', () => {
fastMatch(input)
}),
b.cycle(),
b.complete()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment