mirror of
https://github.com/voltrevo/ValueScript.git
synced 2026-04-18 03:00:27 -04:00
Implement negative indexes for Range.at
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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)),
|
||||
];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user