diff --git a/package.json b/package.json index dade2c1..79e1c3f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "csset", - "version": "0.0.4", + "version": "0.0.5", "description": "experiment to perform algebra of sets with css", "main": "./lib/index.js", "types": "./lib/index.d.ts", diff --git a/src/csset.spec.ts b/src/csset.spec.ts index 7313acb..b3e7ba9 100644 --- a/src/csset.spec.ts +++ b/src/csset.spec.ts @@ -380,4 +380,49 @@ describe('Csset', () => { }); }); }); + + describe('union', () => { + test('should return one set if is superset of the other', () => { + const data = [ + { + sel1: 'div, p, aside, section', + sel2: 'div, p, section.class', + expected: 'div,p,aside,section', + }, + { + sel1: 'div, p, section.class', + sel2: 'div, p, aside, section', + expected: 'div,p,aside,section', + }, + ]; + + data.forEach( d => { + const set1 = new Csset(d.sel1); + const set2 = new Csset(d.sel2); + const result = `${set1} ${operationSymbols.union} ${set2} => ${set1.union(set2)}`; + const expected = `${set1} ${operationSymbols.union} ${set2} => ${d.expected}`; + + expect(result).toEqual(expected); + }); + }); + + test('should remove rules that are subset of others', () => { + const data = [ + { + sel1: 'div, p, aside, section.class', + sel2: 'div, p#id, span, a, section', + expected: 'div,p,aside,span,a,section', + }, + ]; + + data.forEach( d => { + const set1 = new Csset(d.sel1); + const set2 = new Csset(d.sel2); + const result = `${set1} ${operationSymbols.union} ${set2} => ${set1.union(set2)}`; + const expected = `${set1} ${operationSymbols.union} ${set2} => ${d.expected}`; + + expect(result).toEqual(expected); + }); + }); + }); }); diff --git a/src/csset.ts b/src/csset.ts index c73db92..bda07d2 100644 --- a/src/csset.ts +++ b/src/csset.ts @@ -86,7 +86,36 @@ export class Csset { * @param set the set to check with */ subsetOf(set: Csset): boolean { - return set.subsetOf(this); + return set.supersetOf(this); + } + + union(set: Csset): Csset { + if (this.supersetOf(set)) { + return this; + } + + if (this.subsetOf(set)) { + return set; + } + + // return new Csset('unknown'); + + // If one of the sets does not have subsets just return a set with all + if (this.layers || set.layers) { + return new Csset(`${this},${set}`); + } + + // Make union in subsets if possible + const equalSets = this.subsets.filter(thisSet => set.subsets.some(otherSet => `${thisSet}` === `${otherSet}`)); + const uniqueOne = this.subsets.filter(s => !s.subsetOf(set)); + const uniqueTwo = set.subsets.filter(s => !s.subsetOf(this)); + + const equSelector = equalSets.map(s => `${s}`).join(','); + const oneSelector = uniqueOne.map(s => `${s}`).join(','); + const twoSelector = uniqueTwo.map(s => `${s}`).join(','); + + + return new Csset(`${equSelector},${oneSelector},${twoSelector}`); } toString(): string {