Skip to content

Instantly share code, notes, and snippets.

@xantiagoma
Created February 7, 2025 03:51
Show Gist options
  • Save xantiagoma/98ee3a2cffd915fca04b50ff28257489 to your computer and use it in GitHub Desktop.
Save xantiagoma/98ee3a2cffd915fca04b50ff28257489 to your computer and use it in GitHub Desktop.
export function range(
end: number,
config?: { step?: number; direction?: "asc" | "desc" },
): Generator<number>;
export function range(
start: number,
end: number,
config?: { step?: number; direction?: "asc" | "desc" },
): Generator<number>;
export function* range(
startOrEnd: number,
endOrConfig?: number | { step?: number; direction?: "asc" | "desc" },
maybeConfig?: { step?: number; direction?: "asc" | "desc" },
) {
const [start, finalEnd, config] =
typeof endOrConfig === "number"
? [startOrEnd, endOrConfig, maybeConfig ?? {}]
: [0, startOrEnd, endOrConfig ?? {}];
const { step = 1, direction = "asc" } = config;
// For desc direction, swap start and end, adjusting for exclusive upper bound
const [actualStart, actualEnd] =
direction === "desc" ? [finalEnd - 1, start - 1] : [start, finalEnd];
const increment = direction === "asc" ? step : -step;
for (
let i = actualStart;
direction === "asc" ? i < actualEnd : i > actualEnd;
i += increment
) {
yield i;
}
}
export function rangeSync(
end: number,
config?: { step?: number; direction?: "asc" | "desc" },
): number[];
export function rangeSync(
start: number,
end: number,
config?: { step?: number; direction?: "asc" | "desc" },
): number[];
export function rangeSync(
startOrEnd: number,
endOrConfig?: number | { step?: number; direction?: "asc" | "desc" },
maybeConfig?: { step?: number; direction?: "asc" | "desc" },
): number[] {
const [start, finalEnd, config] =
typeof endOrConfig === "number"
? [startOrEnd, endOrConfig, maybeConfig ?? {}]
: [0, startOrEnd, endOrConfig ?? {}];
return [...range(start, finalEnd, config)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment