Skip to content

Commit

Permalink
Add type-safe function for n % 3
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
victorlin committed Nov 21, 2024
1 parent a7578d2 commit ce1f446
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/util/entropyCreateStateFromJsons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand Down

0 comments on commit ce1f446

Please sign in to comment.