perf: faster bem

This commit is contained in:
chenjiahan 2020-03-23 10:29:18 +08:00
parent 13ef031a21
commit fd9993cfa3
2 changed files with 52 additions and 19 deletions

View File

@ -10,30 +10,23 @@
export type Mod = string | { [key: string]: any };
export type Mods = Mod | Mod[];
const ELEMENT = '__';
const MODS = '--';
function gen(name: string, mods?: Mods): string {
if (!mods) {
return '';
}
function join(name: string, el?: string, symbol?: string): string {
return el ? name + symbol + el : name;
}
function prefix(name: string, mods: Mods): Mods {
if (typeof mods === 'string') {
return join(name, mods, MODS);
return ` ${name}--${mods}`;
}
if (Array.isArray(mods)) {
return mods.map(item => <Mod>prefix(name, item));
return mods.reduce<string>((ret, item) => ret + gen(name, item), '');
}
const ret: Mods = {};
if (mods) {
Object.keys(mods).forEach(key => {
ret[name + MODS + key] = mods[key];
});
}
return ret;
return Object.keys(mods).reduce(
(ret, key) => ret + (mods[key] ? gen(name, key) : ''),
''
);
}
export function createBEM(name: string) {
@ -42,9 +35,10 @@ export function createBEM(name: string) {
mods = el;
el = '';
}
el = join(name, el, ELEMENT);
return mods ? [el, prefix(el, mods)] : el;
el = el ? `${name}__${el}` : name;
return `${el}${gen(el, mods)}`;
};
}

View File

@ -0,0 +1,39 @@
import { createBEM } from '../create/bem';
test('bem', () => {
const bem = createBEM('button');
expect(bem()).toEqual('button');
expect(bem('text')).toEqual('button__text');
expect(bem({ disabled: false })).toEqual('button');
expect(bem({ disabled: true })).toEqual('button button--disabled');
expect(bem('text', { disabled: true })).toEqual(
'button__text button__text--disabled'
);
expect(bem(['disabled', 'primary'])).toEqual(
'button button--disabled button--primary'
);
expect(bem([])).toEqual('button');
expect(bem(null)).toEqual('button');
expect(bem([null])).toEqual('button');
expect(bem(['disabled', ''])).toEqual('button button--disabled');
expect(bem(['disabled', undefined])).toEqual('button button--disabled');
expect(bem('text', ['disabled', 'primary'])).toEqual(
'button__text button__text--disabled button__text--primary'
);
expect(bem('text', [{ disabled: true }, 'primary'])).toEqual(
'button__text button__text--disabled button__text--primary'
);
});