From 3f004b58a4460fae228d11e9cb08cd4726933818 Mon Sep 17 00:00:00 2001 From: Benny Neugebauer Date: Mon, 13 Jan 2025 13:12:50 +0100 Subject: [PATCH] refactor!: Make "getResult" return null (#746) --- src/Indicator.test.ts | 13 +++++++++++++ src/Indicator.ts | 21 ++++++++++++++++----- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/Indicator.test.ts b/src/Indicator.test.ts index 0e9e3bba..77fe4215 100644 --- a/src/Indicator.test.ts +++ b/src/Indicator.test.ts @@ -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(); diff --git a/src/Indicator.ts b/src/Indicator.ts index 70cccc03..d6914418 100644 --- a/src/Indicator.ts +++ b/src/Indicator.ts @@ -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 | null; + interface Indicator { - 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; + getResult(): Nullable; + getResultOrThrow(): Result; + replace(input: Input): Nullable; + update(input: Input, replace: boolean): Nullable; + updates(input: Input[], replace: boolean): Nullable; } export abstract class TechnicalIndicator implements Indicator { protected result: Result | undefined; + getResult() { + try { + return this.getResultOrThrow(); + } catch { + return null; + } + } + getResultOrThrow() { if (this.result === undefined) { throw new NotEnoughDataError();