mirror of
https://github.com/voltrevo/ValueScript.git
synced 2026-04-18 03:00:27 -04:00
Start working on range
This commit is contained in:
56
inputs/passing/helpers/range.ts
Normal file
56
inputs/passing/helpers/range.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
export default function range<T = never>(iter?: Iterable<T> | Iterator<T>) {
|
||||
return new Range<T>(iter);
|
||||
}
|
||||
|
||||
class Range<T = never> implements Iterable<T> {
|
||||
iterable: Iterable<T>;
|
||||
|
||||
constructor(iter?: Iterable<T> | Iterator<T>) {
|
||||
if (iter === undefined) {
|
||||
this.iterable = [];
|
||||
} else if (isIterator(iter)) {
|
||||
this.iterable = {
|
||||
[Symbol.iterator]: () => iter,
|
||||
};
|
||||
} else {
|
||||
this.iterable = iter;
|
||||
}
|
||||
}
|
||||
|
||||
[Symbol.iterator]() {
|
||||
return this.iterable[Symbol.iterator]();
|
||||
}
|
||||
|
||||
limit(n: number) {
|
||||
const iterable = this.iterable;
|
||||
|
||||
function* res() {
|
||||
let i = 0;
|
||||
|
||||
for (const x of iterable) {
|
||||
if (i >= n) {
|
||||
break;
|
||||
}
|
||||
|
||||
yield x;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return range(res());
|
||||
}
|
||||
|
||||
count() {
|
||||
let i = 0;
|
||||
|
||||
for (const _x of this.iterable) {
|
||||
i++;
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
function isIterator<T>(iter: Iterable<T> | Iterator<T>): iter is Iterator<T> {
|
||||
return (iter as unknown as Record<string, unknown>).next !== undefined;
|
||||
}
|
||||
12
inputs/passing/iteration/testRange.ts
Normal file
12
inputs/passing/iteration/testRange.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
// test_output! [0,2,[2,3,5,7,11]]
|
||||
|
||||
import range from "../helpers/range.ts";
|
||||
import { primes } from "../projEuler/helpers/primes.ts";
|
||||
|
||||
export default function main() {
|
||||
return [
|
||||
range().count(),
|
||||
range([1, 2, 3]).limit(2).count(),
|
||||
[...range(primes()).limit(5)],
|
||||
];
|
||||
}
|
||||
@@ -29,7 +29,15 @@ module.exports = {
|
||||
"comma-dangle": ["error", "always-multiline"],
|
||||
"react/react-in-jsx-scope": "off",
|
||||
"quote-props": ["error", "consistent-as-needed"],
|
||||
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
caughtErrorsIgnorePattern: "^_",
|
||||
destructuredArrayIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
"prettier/prettier": "error",
|
||||
"no-constant-condition": "off",
|
||||
"no-empty": ["error", { allowEmptyCatch: true }],
|
||||
|
||||
Reference in New Issue
Block a user