Skip to content

Commit c7607e1

Browse files
committed
refactor: add neverthrow to range
BREAKING CHANGE
1 parent d7414d0 commit c7607e1

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

src/__tests__/range.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ import { range } from '../range.js';
44

55
describe('range', () => {
66
it('should return an array equal in length to the range', () => {
7-
const arr = range(10);
7+
const arr = range(10)._unsafeUnwrap();
88
expect(arr.length).toBe(10);
99
});
10-
it('should throw an error if the start is equal to the end', () => {
11-
expect(() => range(1, 1)).toThrow();
10+
it('should return an error if the start is equal to the end', () => {
11+
expect(range(1, 1).isErr()).toBe(true);
1212
});
1313
});

src/range.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
1+
import { ok } from 'neverthrow';
2+
import type { Result } from 'neverthrow';
3+
4+
import { ValueException } from './exception.js';
5+
16
/** Return an array of integers between 0 (inclusive) and `end` (not inclusive) */
2-
export function range(end: number): readonly number[];
7+
export function range(end: number): Result<readonly number[], typeof ValueException.Instance>;
38

49
/** Return an array of integers between `start` (inclusive) and `end` (not inclusive) */
5-
export function range(start: number, end: number): readonly number[];
10+
export function range(start: number, end: number): Result<readonly number[], typeof ValueException.Instance>;
611

7-
export function range(...args: number[]): readonly number[] {
12+
export function range(...args: number[]): Result<readonly number[], typeof ValueException.Instance> {
813
const start = args.length === 2 ? args[0]! : 0;
914
const end = args.length === 2 ? args[1]! : args[0]!;
1015

1116
if (start >= end) {
12-
throw new Error(`End of range '${end}' must be greater than start '${start}'`);
17+
return ValueException.asErr(`End of range '${end}' must be greater than start '${start}'`);
1318
}
1419

1520
const values: number[] = [];
1621
for (let i = start; i < end; i++) {
1722
values.push(i);
1823
}
19-
return values;
24+
return ok(values);
2025
}

0 commit comments

Comments
 (0)