Skip to content

Commit

Permalink
refactor!: Make "getResult" return null (#746)
Browse files Browse the repository at this point in the history
  • Loading branch information
bennycode authored Jan 13, 2025
1 parent c022140 commit 3f004b5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/Indicator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ describe('Indicator', () => {
});
});

describe('getResult', () => {
it('returns the result if an indicator is stable', () => {
const itc = new IndicatorTestClass();
itc.add(1);
expect(itc.getResult()?.toFixed()).toBe('1');
});

it("returns null if an indicator isn't stable", () => {
const itc = new IndicatorTestClass();
expect(itc.getResult()).toBe(null);
});
});

describe('getResultOrThrow', () => {
it('throws an error when there is not enough input data', () => {
const itc = new IndicatorTestClass();
Expand Down
21 changes: 16 additions & 5 deletions src/Indicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,29 @@ import type {BigSource} from 'big.js';
import {NotEnoughDataError} from './error/NotEnoughDataError.js';
import {getLastFromForEach} from './util/getLastFromForEach.js';

type Nullable<Result> = Result | null;

interface Indicator<Result = Big, Input = BigSource> {
getResultOrThrow(): Result;
isStable: boolean;
add(input: Input): Result | null;
replace(input: Input): Result | null;
update(input: Input, replace: boolean): Result | null;
updates(input: Input[], replace: boolean): Result | null;
add(input: Input): Nullable<Result>;
getResult(): Nullable<Result>;
getResultOrThrow(): Result;
replace(input: Input): Nullable<Result>;
update(input: Input, replace: boolean): Nullable<Result>;
updates(input: Input[], replace: boolean): Nullable<Result>;
}

export abstract class TechnicalIndicator<Result, Input> implements Indicator<Result, Input> {
protected result: Result | undefined;

getResult() {
try {
return this.getResultOrThrow();
} catch {
return null;
}
}

getResultOrThrow() {
if (this.result === undefined) {
throw new NotEnoughDataError();
Expand Down

0 comments on commit 3f004b5

Please sign in to comment.