Implement negative indexes for Range.at

This commit is contained in:
Andrew Morris
2023-07-06 14:36:29 +10:00
parent fcc140c46c
commit eb95deeb5d
2 changed files with 25 additions and 2 deletions

View File

@@ -161,8 +161,28 @@ export default class Range<T = never> implements Iterable<T> {
return new Range(res());
}
// TODO: Negative indexes
at(n: number) {
if (n < 0) {
if (n === -1) {
return this.last();
}
let buf: T[] = [];
let len = -n;
let i = 0;
for (const x of this.iterable) {
buf[i % len] = x;
i++;
}
if (buf.length < len) {
return undefined;
}
return buf[i % len];
}
let i = 0;
for (const x of this.iterable) {

View File

@@ -1,4 +1,4 @@
// test_output! [0,2,[2,3,5,7,11],[11,31,41,61,71],547]
// test_output! [0,2,[2,3,5,7,11],[11,31,41,61,71],547,"v","a",undefined]
import Range from "../helpers/Range.ts";
import { primes } from "../projEuler/helpers/primes.ts";
@@ -10,5 +10,8 @@ export default function main() {
[...Range.from(primes()).limit(5)],
[...Range.from(primes()).filter((p) => p % 5 === 1).limit(5)],
Range.from(primes()).at(100),
Range.from(["abcdefghijklmnopqrstuvwxyz"].at(-5)),
Range.from(["abcdefghijklmnopqrstuvwxyz"].at(-26)),
Range.from(["abcdefghijklmnopqrstuvwxyz"].at(-27)),
];
}