Skip to content

Commit

Permalink
update: add range generator
Browse files Browse the repository at this point in the history
  • Loading branch information
calebpitan committed Nov 11, 2024
1 parent 0888803 commit 9123ece
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/common/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,31 @@ export const turnoff = (bits: number, index: number) => {
* @returns The converted string
*/
export const pascalCase = (s: string) => startCase(camelCase(s)).replace(/ /g, '')

/**
* Generate a range of integers from `0` to `stop`
* @param stop The number, exclusive, at which the range generator stops
*/
export function range(stop: number): Generator<number>
/**
* Generate a range of integers from `start` to `stop` taking `step`
* progressively
*
* @param start The number from which the range generator begins
* @param stop The number, exclusive, at which the range generator stops
* @param step The arithmetic progression for the range generator
*/
export function range(start: number, stop: number, step?: number): Generator<number>
export function* range(stopOrStart: number, stop?: number, step?: number) {
// TODO: make range work with integers only due to inconsistencies with float arithmetic
let start = 0
;({ start, stop, step } =
stop === undefined
? { start, stop: stopOrStart, step: 1 }
: { start: stopOrStart, stop: stop, step: Math.sign(stop - stopOrStart) })

const order = ((a: number, b: number) => (i: number) => (a < b ? i < b : i > b))(start, stop)
for (let i = start; order(i); i += step) {
yield i
}
}

0 comments on commit 9123ece

Please sign in to comment.