From c14a8fbfef00269dd24dc3d5960bb777eae8e198 Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Sat, 13 Mar 2021 11:03:04 +0000 Subject: [PATCH] refactor(dcons): dedupe OOB error handling --- packages/dcons/src/dcons.ts | 17 ++++++----------- packages/dcons/src/sol.ts | 4 ++-- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/packages/dcons/src/dcons.ts b/packages/dcons/src/dcons.ts index a1f9df65f3..c887a32ba5 100644 --- a/packages/dcons/src/dcons.ts +++ b/packages/dcons/src/dcons.ts @@ -1,5 +1,4 @@ -import { - assert, +import type { Comparator, Fn, IClear, @@ -12,12 +11,12 @@ import { ISeq, ISeqable, IStack, - Predicate, + Predicate } from "@thi.ng/api"; import { isArrayLike } from "@thi.ng/checks"; import { compare } from "@thi.ng/compare"; import { equiv } from "@thi.ng/equiv"; -import { illegalArgs } from "@thi.ng/errors"; +import { ensureIndex, illegalArgs } from "@thi.ng/errors"; import { IRandom, SYSTEM } from "@thi.ng/random"; import { IReducible, isReduced, ReductionFn } from "@thi.ng/transducers"; @@ -223,7 +222,7 @@ export class DCons if (n <= 0) { return this.cons(x); } else { - this.ensureIndex(n); + ensureIndex(n, 0, this._length); return this.insertBefore(this.nthCellUnsafe(n), x); } } @@ -235,7 +234,7 @@ export class DCons if (n >= this._length - 1) { return this.push(x); } else { - this.ensureIndex(n); + ensureIndex(n, 0, this._length); return this.insertAfter(this.nthCellUnsafe(n), x); } } @@ -307,7 +306,7 @@ export class DCons if (at < 0) { at += this._length; } - this.ensureIndex(at); + ensureIndex(at, 0, this._length); cell = this.nthCellUnsafe(at); } else { cell = at; @@ -640,10 +639,6 @@ export class DCons return [...this]; } - protected ensureIndex(i: number) { - assert(i >= 0 && i < this._length, `index out of range: ${i}`); - } - protected nthCellUnsafe(n: number) { let cell: ConsCell, dir: keyof ConsCell; if (n <= this._length >> 1) { diff --git a/packages/dcons/src/sol.ts b/packages/dcons/src/sol.ts index 075602a775..9cbfebcd68 100644 --- a/packages/dcons/src/sol.ts +++ b/packages/dcons/src/sol.ts @@ -1,5 +1,5 @@ import type { Fn2, Predicate } from "@thi.ng/api"; -import { illegalArgs } from "@thi.ng/errors"; +import { outOfBounds } from "@thi.ng/errors"; import { ConsCell, DCons } from "./dcons"; /** @@ -44,7 +44,7 @@ export class SOL extends DCons { setNth(n: number, v: T) { const cell = this.nthCell(n); - !cell && illegalArgs(`index out of bounds: ${n}`); + !cell && outOfBounds(n); this._reorder(this, cell!).value = v; return this; }