for i in range(10):
print(i)
#Cool
/**
* @param {...number} args
*/
const range = (...args) => {
const rangeGen = function* (from = 0, to = Infinity, step = 1) {
for (let v = from; v < to; v += step) {
yield v;
}
};
return args.length === 0
? rangeGen(undefined, undefined, undefined)
: args.length === 1
? rangeGen(undefined, args[0], undefined)
: args.length === 2
? rangeGen(args[0], args[1], undefined)
: rangeGen(...args);
};
for (const v of range(2, 10)) {
console.log(v);
// 2 ~Up to 9 are output in order
}
The range
function returns the result of executing the generator function. It is a wrapper that just distributes the arguments to the generator function.
rangeGen
is the generator function.
――What is a generator? --A relatively new feature of JavaScript added in ES2015 ――What are you generating? --Generate repeatable objects ――What is repetition?
for-of
--Spread syntax (... iterator
)
--Split assignment (const [hoge, huga] = iterator;
)
――It is. Perhaps
-Isn't it an array?
--Can handle infinityFor details on how to use the generator function, please read MDN.
For the time being, I am making a guy who can enumerate the numbers from from
to to
.
Now you can also for (const i of range (10)) {
in JavaScript.
Personally, Python's sledding is troublesome because you have to pay attention to the order of the arguments. So below (TypeScript).
const range = function* ({
start = 0,
stop = Infinity,
step = 1,
}: {
start?: number;
stop: number;
step?: number;
}) {
while (start < stop) {
yield start;
start += step;
}
};
for (const v of range({ stop: 10 })) {
console.log(v);
}
that's all.
Recommended Posts