From ce1f446ac7d01227964acd0eba9d5085dac0533e Mon Sep 17 00:00:00 2001 From: Victor Lin <13424970+victorlin@users.noreply.github.com> Date: Thu, 21 Nov 2024 11:33:50 -0800 Subject: [PATCH] Add type-safe function for n % 3 At first, I disabled @typescript-eslint/consistent-type-assertions for the type assertion in the original code, but that ended up polluting the _frame() function with details unrelated to the direct purpose of the function. Extracting the modulus operation into a separate function and adding the details there felt like a better scope. --- src/util/entropyCreateStateFromJsons.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/util/entropyCreateStateFromJsons.ts b/src/util/entropyCreateStateFromJsons.ts index f9d43e416..fddd5d01b 100644 --- a/src/util/entropyCreateStateFromJsons.ts +++ b/src/util/entropyCreateStateFromJsons.ts @@ -332,9 +332,24 @@ function _frame( genomeLength: number, positiveStrand: boolean, ): Frame { - return (positiveStrand ? - (start+phase-1)%3 : - Math.abs((end-phase-genomeLength)%3)) as Frame; + return positiveStrand ? + _mod3(start+phase-1) : + _mod3(end-phase-genomeLength); +} + +/** + * Type-safe modulo operation. Return value is unsigned (i.e. non-negative). + */ +function _mod3(n: number): 0 | 1 | 2 { + if (!Number.isInteger(n)) { + throw new Error(`${n} is not an integer.`); + } + + /* TypeScript cannot infer the exact range of values from a modulo operation, + * so it is manually provided. + */ + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + return (Math.abs(n) % 3) as 0 | 1 | 2 } /**