Skip to content

Commit

Permalink
feat(StyleClassHelper): add putIfPresent method
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusNotheis committed May 25, 2020
1 parent 97158a3 commit f955a32
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 8 deletions.
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

0 comments on commit f955a32

Please sign in to comment.