Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(StyleClassHelper): add putIfPresent method #539

Merged
merged 2 commits into from
May 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/base/src/styling/StyleClassHelper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { StyleClassHelper } from './StyleClassHelper';

describe('StyleClassHelper', () => {
test('add class names', () => {
const helper = StyleClassHelper.of('class1', 'class2');
expect(helper.className).toEqual(`class1 class2`);
});

test('put new classes', () => {
const helper = StyleClassHelper.of('firstClass');
helper.put('secondClass');
expect(helper.className).toEqual(`firstClass secondClass`);
});

test('putIfPresent', () => {
const helper = StyleClassHelper.of('firstClass');
helper.put('secondClass');
helper.putIfPresent('ifPresent1');
helper.putIfPresent('ifPresent2', 'ifPresent3');
helper.putIfPresent(true === false && 'shouldNotBeThere1', 'a' === 'a' && 'ifPresent4');

expect(helper.className).toEqual('firstClass secondClass ifPresent1 ifPresent2 ifPresent3 ifPresent4');
});

test('className, toString and valueOf return same value', () => {
const helper = StyleClassHelper.of('class1', 'class2');
expect(helper.toString()).toEqual(`class1 class2`);
expect(helper.valueOf()).toEqual(`class1 class2`);
expect(helper.className).toEqual(`class1 class2`);
});
});
28 changes: 20 additions & 8 deletions packages/base/src/styling/StyleClassHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,40 @@
* Created by d059190 at 16.03.18
*/

class StyleClassHelper extends String {
class StyleClassHelper {
private classes: string[] = [];

constructor(...classes: string[]) {
super();
this.classes = [...classes];
}

put(...clazz: string[]) {
put(...clazz: string[]): StyleClassHelper {
this.classes.push(...clazz);
return this;
}

valueOf() {
return this.classes.join(' ');
putIfPresent(...clazzes: (string | null | undefined)[]): StyleClassHelper {
for (const clazz of clazzes) {
if (clazz) {
this.classes.push(clazz);
}
}
return this;
}

valueOf(): string {
return this.className;
}

toString() {
return this.valueOf();
toString(): string {
return this.className;
}

get className(): string {
return this.classes.join(' ');
}

static of(...classes: string[]) {
static of(...classes: string[]): StyleClassHelper {
return new StyleClassHelper().put(...classes);
}
}
Expand Down