simplified finding duplicates
This commit is contained in:
@@ -9,29 +9,18 @@ export class Script extends BaseEntity<string> implements IScript {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static ensureCodeHasUniqueLines(name: string, code: string): void {
|
private static ensureCodeHasUniqueLines(name: string, code: string): void {
|
||||||
const lines = code.split('\n');
|
const lines = code.split('\n')
|
||||||
|
.map((line) => this.mayBeUniqueLine(line));
|
||||||
if (lines.length === 0) {
|
if (lines.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const duplicateLines = new Array<string>();
|
const duplicateLines = lines.filter((e, i, a) => a.indexOf(e) !== i);
|
||||||
const uniqueLines = new Set<string>();
|
|
||||||
let validatedLineCount = 0;
|
|
||||||
for (const line of lines) {
|
|
||||||
if (!this.isUniqueLine(line)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
uniqueLines.add(line);
|
|
||||||
if (uniqueLines.size !== validatedLineCount + 1) {
|
|
||||||
duplicateLines.push(line);
|
|
||||||
}
|
|
||||||
validatedLineCount++;
|
|
||||||
}
|
|
||||||
if (duplicateLines.length !== 0) {
|
if (duplicateLines.length !== 0) {
|
||||||
throw Error(`Duplicates detected in script "${name}":\n ${duplicateLines.join('\n')}`);
|
throw Error(`Duplicates detected in script "${name}":\n ${duplicateLines.join('\n')}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static isUniqueLine(codeLine: string): boolean {
|
private static mayBeUniqueLine(codeLine: string): boolean {
|
||||||
const trimmed = codeLine.trim();
|
const trimmed = codeLine.trim();
|
||||||
if (trimmed === ')' || trimmed === '(') { // "(" and ")" are used often in batch code
|
if (trimmed === ')' || trimmed === '(') { // "(" and ")" are used often in batch code
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
17
tests/unit/domain/Script.spec.ts
Normal file
17
tests/unit/domain/Script.spec.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import 'mocha';
|
||||||
|
import { expect } from 'chai';
|
||||||
|
import { Script } from '@/domain/Script';
|
||||||
|
|
||||||
|
describe('Script', () => {
|
||||||
|
|
||||||
|
it('cannot construct with duplicate lines', async () => {
|
||||||
|
// arrange
|
||||||
|
const code = 'duplicate\nduplicate\ntest\nduplicate';
|
||||||
|
|
||||||
|
// act
|
||||||
|
function construct() { return new Script('ScriptName', code, []); }
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(construct).to.throw();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user