From 57037aaefcc0e80f0f4719cea89568490a731028 Mon Sep 17 00:00:00 2001 From: undergroundwires Date: Mon, 6 Jan 2020 18:19:28 +0100 Subject: [PATCH] simplified finding duplicates --- src/domain/Script.ts | 19 ++++--------------- tests/unit/domain/Script.spec.ts | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 15 deletions(-) create mode 100644 tests/unit/domain/Script.spec.ts diff --git a/src/domain/Script.ts b/src/domain/Script.ts index aefda55b..b4e4853e 100644 --- a/src/domain/Script.ts +++ b/src/domain/Script.ts @@ -9,29 +9,18 @@ export class Script extends BaseEntity implements IScript { } 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) { return; } - const duplicateLines = new Array(); - const uniqueLines = new Set(); - 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++; - } + const duplicateLines = lines.filter((e, i, a) => a.indexOf(e) !== i); if (duplicateLines.length !== 0) { 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(); if (trimmed === ')' || trimmed === '(') { // "(" and ")" are used often in batch code return false; diff --git a/tests/unit/domain/Script.spec.ts b/tests/unit/domain/Script.spec.ts new file mode 100644 index 00000000..56bfb999 --- /dev/null +++ b/tests/unit/domain/Script.spec.ts @@ -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(); + }); +});