File tree Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ function * range ( first , second , step = 1 ) {
4
+ let current ;
5
+ let end ;
6
+
7
+ if ( second === undefined ) {
8
+ current = 0 ;
9
+ end = first ;
10
+ } else {
11
+ current = first ;
12
+ end = second ;
13
+ }
14
+
15
+ if ( step === 0 ) {
16
+ throw new Error ( 'illegal step' ) ;
17
+ }
18
+
19
+ while ( current < end && step > 0 ||
20
+ current > end && step < 0 ) {
21
+ yield current ;
22
+ current += step ;
23
+ }
24
+ }
25
+
26
+ console . log ( [
27
+ [ ...range ( 10 ) ] ,
28
+ [ ...range ( 3 , 18 ) ] ,
29
+ [ ...range ( 2 , 15 , 2 ) ] ,
30
+ [ ...range ( 10 , 0 , - 1 ) ] ,
31
+ ] ) ;
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ class Range {
4
+ constructor ( first , second , step = 1 ) {
5
+ if ( second === undefined ) {
6
+ this . start = 0 ;
7
+ this . end = first ;
8
+ } else {
9
+ this . start = first ;
10
+ this . end = second ;
11
+ }
12
+
13
+ if ( step === 0 ) {
14
+ throw new Error ( 'illegal step' ) ;
15
+ }
16
+
17
+ this . step = step ;
18
+ }
19
+
20
+ [ Symbol . iterator ] ( ) {
21
+ const { start, end, step } = this ;
22
+ let current = start ;
23
+ return {
24
+ next ( ) {
25
+ if ( current === undefined ) {
26
+ return { value : undefined , done : true } ;
27
+ }
28
+
29
+ if ( current >= end && step > 0 ||
30
+ current <= end && step < 0 ) {
31
+ let value = current ;
32
+ current = undefined ;
33
+ return { value, done : true } ;
34
+ }
35
+
36
+ let value = current ;
37
+ current += step ;
38
+ return { value, done : false } ;
39
+ }
40
+ } ;
41
+ }
42
+ }
43
+
44
+ console . log ( [
45
+ [ ...new Range ( 10 ) ] ,
46
+ [ ...new Range ( 3 , 18 ) ] ,
47
+ [ ...new Range ( 2 , 15 , 2 ) ] ,
48
+ [ ...new Range ( 10 , 0 , - 1 ) ] ,
49
+ ] ) ;
You can’t perform that action at this time.
0 commit comments