From 1c6af8fa9d640ea914632110b22d94b713a19866 Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Wed, 29 Apr 2020 22:19:08 +0200 Subject: [PATCH] fix --- lib/Element.ts | 17 +++++++++++++---- test/Node.ts | 12 +++++++++++- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/lib/Element.ts b/lib/Element.ts index 160c16c..9c625d3 100644 --- a/lib/Element.ts +++ b/lib/Element.ts @@ -1,5 +1,5 @@ export class Element { - public name: string; + private _name = ''; protected parent_name: string; public get full_name (): string { @@ -8,14 +8,23 @@ export class Element { return this.name; } + public get name (): string { + return this._name; + } + + public set name (val: string) { + const new_name = val.replace (/[^a-z0-9]/giu, '') + .replace (/^[0-9]+/iu, ''); + if (new_name === '') + throw new Error ('invalid name specified'); + this._name = new_name; + } + public get parent (): string { return this.parent_name; } public constructor (name: string, parent = '') { - const regex = /^[a-z_][a-z_0-9]+$/iu; - if (!regex.test (name)) - throw new Error ('invalid name specified'); this.name = name; this.parent_name = parent; } diff --git a/test/Node.ts b/test/Node.ts index 829cace..561fa24 100644 --- a/test/Node.ts +++ b/test/Node.ts @@ -49,8 +49,18 @@ test ('serialize table', (t) => { }); test ('adhere to naming convention', (t) => { + const n = new Node ('invalid.name', 'parent'); + t.is (n.name, 'invalidname'); +}); + +test ('throw on invalid name', (t) => { t.throws (() => { - const n = new Node ('invalid.name', 'parent'); + const n = new Node ('564#+-.,/@', 'parent'); return n.toString (); }, { message: 'invalid name specified' }); }); + +test ('leave numbers after the first letter', (t) => { + const n = new Node ('i123nvalid.name', 'parent'); + t.is (n.name, 'i123nvalidname'); +});