Skip to content

Commit

Permalink
refactor(dcons): dedupe OOB error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Mar 13, 2021
1 parent a6d9731 commit c14a8fb
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
17 changes: 6 additions & 11 deletions packages/dcons/src/dcons.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
assert,
import type {
Comparator,
Fn,
IClear,
Expand All @@ -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";

Expand Down Expand Up @@ -223,7 +222,7 @@ export class DCons<T>
if (n <= 0) {
return this.cons(x);
} else {
this.ensureIndex(n);
ensureIndex(n, 0, this._length);
return this.insertBefore(this.nthCellUnsafe(n), x);
}
}
Expand All @@ -235,7 +234,7 @@ export class DCons<T>
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);
}
}
Expand Down Expand Up @@ -307,7 +306,7 @@ export class DCons<T>
if (at < 0) {
at += this._length;
}
this.ensureIndex(at);
ensureIndex(at, 0, this._length);
cell = this.nthCellUnsafe(at);
} else {
cell = at;
Expand Down Expand Up @@ -640,10 +639,6 @@ export class DCons<T>
return [...this];
}

protected ensureIndex(i: number) {
assert(i >= 0 && i < this._length, `index out of range: ${i}`);
}

protected nthCellUnsafe(n: number) {
let cell: ConsCell<T>, dir: keyof ConsCell<T>;
if (n <= this._length >> 1) {
Expand Down
4 changes: 2 additions & 2 deletions packages/dcons/src/sol.ts
Original file line number Diff line number Diff line change
@@ -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";

/**
Expand Down Expand Up @@ -44,7 +44,7 @@ export class SOL<T> extends DCons<T> {

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;
}
Expand Down

0 comments on commit c14a8fb

Please sign in to comment.