Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created January 14, 2021 21:50
Show Gist options
  • Select an option

  • Save jtmthf/64c238367ed68347ac55a2b5bd77a660 to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/64c238367ed68347ac55a2b5bd77a660 to your computer and use it in GitHub Desktop.
type IterableRange = IterableIterator<number> & {
start: number;
end: number;
step: number;
};
function range(
startOrEnd: number,
maybeEnd?: number,
maybeStep?: number
): IterableRange {
const start = maybeEnd == null ? 0 : startOrEnd;
const end = maybeEnd == null ? startOrEnd : maybeEnd;
const step = maybeStep == null ? (end < 0 ? -1 : 1) : maybeStep;
const predicate =
step < 0
? (current: number) => current > end
: (current: number) => current < end;
return Object.assign(
(function* () {
let current = start;
while (predicate(current)) {
yield current;
current += step;
}
})(),
{ start, end, step }
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment