-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
85 lines (69 loc) · 2.69 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// 73: Generator - `return` inside a generator is special (solution)
// To do: make all tests pass, leave the assert lines unchanged!
describe('`return` in a generator function is special', function() {
describe('the returned value is an IteratorResult (just like any value returned via `yield`)', function() {
it('returns an IteratorResult (an object with the properties `value` and `done`)', function() {
function* generatorFunction() { return 1; }
const returned = generatorFunction().next();
const propertyNames = ['value', 'done'];
assert.deepEqual(Object.keys(returned), propertyNames);
});
it('the property `value` is the value given after the `return` statement', function() {
function* generatorFunction() { return 23; }
const {value} = generatorFunction().next();
assert.equal(value, 23);
});
it('the property `done` is true', function() {
function* generatorFunction() { return 42; }
const {done} = generatorFunction().next();
assert.equal(done, true);
});
it('NOTE: `yield` does not return `done=true` but `done=false`!', function() {
function* generatorFunction() { yield 1; }
const returned = generatorFunction().next();
assert.deepEqual(returned, {value: 1, done: false});
});
it('a missing `return` returns {value: undefined, done: true}', function() {
function* generatorFunction() { return; }
const returned = generatorFunction().next();
assert.deepEqual(returned, {value: void 0, done: true});
});
});
describe('mixing `return` and `yield`', function() {
function* generatorFunctionWithYieldAndReturn() {
yield 1;
return 2;
}
it('is possible', function() {
const iterator = generatorFunctionWithYieldAndReturn();
const values = [
iterator.next(),
iterator.next()
];
assert.deepEqual(values, [{value: 1, done: false}, {value: 2, done: true}]);
});
it('the mix behaves different to two `yield`s', function() {
const iterator = generatorFunctionWithYieldAndReturn();
const values = [1];
assert.deepEqual(Array.from(iterator), values);
});
it('two `yield`s returning values', function() {
function* generatorFunctionWithTwoYields() {
yield 1;
yield 2;
}
assert.deepEqual(Array.from(generatorFunctionWithTwoYields()), [1, 2]);
});
it('returning a yielded value', function() {
function* generatorFunction() {
return yield 1;
}
const iterator = generatorFunction();
const values = [
iterator.next().value,
iterator.next(2).value
];
assert.deepEqual(values, [1, 2]);
});
});
});