2018-04-06 17:27:24 +02:00
|
|
|
import Utils from "../Utils";
|
|
|
|
import Operation from "../Operation";
|
2018-04-04 18:37:19 +02:00
|
|
|
|
|
|
|
/**
|
2018-04-06 17:27:24 +02:00
|
|
|
* Set Union operation
|
2018-04-04 18:37:19 +02:00
|
|
|
*/
|
2018-04-06 17:27:24 +02:00
|
|
|
class SetUnion extends Operation {
|
2018-04-04 18:37:19 +02:00
|
|
|
|
|
|
|
/**
|
2018-04-06 17:27:24 +02:00
|
|
|
* Set Union constructor
|
2018-04-04 18:37:19 +02:00
|
|
|
*/
|
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
|
|
|
|
this.name = "Set Union";
|
2018-04-06 17:27:24 +02:00
|
|
|
this.module = "Default";
|
2018-04-04 18:37:19 +02:00
|
|
|
this.description = "Get the union of two sets";
|
2018-04-06 17:27:24 +02:00
|
|
|
this.inputType = "string";
|
|
|
|
this.outputType = "string";
|
|
|
|
this.args = [
|
|
|
|
{
|
|
|
|
name: "Sample delimiter",
|
|
|
|
type: "binaryString",
|
|
|
|
value: Utils.escapeHtml("\\n\\n")
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "Item delimiter",
|
|
|
|
type: "binaryString",
|
|
|
|
value: ","
|
|
|
|
},
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Validate input length
|
|
|
|
* @param {Object[]} sets
|
|
|
|
* @throws {Error} if not two sets
|
|
|
|
*/
|
|
|
|
validateSampleNumbers(sets) {
|
|
|
|
if (!sets || (sets.length !== 2)) {
|
|
|
|
throw "Incorrect number of sets, perhaps you need to modify the sample delimiter or add more samples?";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Run the union operation
|
|
|
|
* @param input
|
|
|
|
* @param args
|
|
|
|
*/
|
|
|
|
run(input, args) {
|
|
|
|
[this.sampleDelim, this.itemDelimiter] = args;
|
|
|
|
const sets = input.split(this.sampleDelim);
|
|
|
|
|
|
|
|
try {
|
|
|
|
this.validateSampleNumbers(sets);
|
|
|
|
} catch (e) {
|
|
|
|
return e;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Utils.escapeHtml(this.runUnion(...sets.map(s => s.split(this.itemDelimiter))));
|
2018-04-04 18:37:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the union of the two sets.
|
|
|
|
*
|
|
|
|
* @param {Object[]} a
|
|
|
|
* @param {Object[]} b
|
|
|
|
* @returns {Object[]}
|
|
|
|
*/
|
|
|
|
runUnion(a, b) {
|
|
|
|
const result = {};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Only add non-existing items
|
|
|
|
* @param {Object} hash
|
|
|
|
*/
|
|
|
|
const addUnique = (hash) => (item) => {
|
|
|
|
if (!hash[item]) {
|
|
|
|
hash[item] = true;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
a.map(addUnique(result));
|
|
|
|
b.map(addUnique(result));
|
|
|
|
|
|
|
|
return Object.keys(result).join(this.itemDelimiter);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default SetUnion;
|