Created
January 31, 2018 23:33
-
-
Save steve-taylor/d929ae75a992ae54922abac32ff5c776 to your computer and use it in GitHub Desktop.
Create an Iterable over a sequence of numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function *sequence(...args) { | |
const start = args.length < 2 ? 0 : args[0]; | |
const end = args[args.length < 2 ? 0 : 1] || 0; | |
const step = args.length < 3 ? 1 : args[2]; | |
for (let i = start; i < end; i += step) { | |
yield i; | |
} | |
} | |
// | |
// Examples: | |
// | |
// |-----------------------------------------|----------------| | |
// | Code | Output | | |
// |-----------------------------------------|----------------| | |
// | for (const i of sequence(3)) { | 0 | | |
// | console.log(i); | 1 | | |
// | } | 2 | | |
// |-----------------------------------------|----------------| | |
// | console.log([...sequence(3, 7)]); | [3, 4, 5, 6] | | |
// |-----------------------------------------|----------------| | |
// | console.log([...sequence(4, 13, 3)]); | [4, 8, 12] | | |
// |-----------------------------------------|----------------| | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment