December 12, 2018
TestsSource
- dynamic labels? (can use variables for labels?)
Source Code
The source code we wrote during the event.
labels.spec.js
import assert from 'assert';
it('a label must be defined before its usage', () => {
assert.throws(() => eval(`
continue label0;
label0;
`)
);
});
it('label followed by let throws', () => {
assert.throws(() => eval(`
label:
let a1 = 1;
`)
);
});
it('label followed by var does not throw', () => {
assert.doesNotThrow(() => eval(`
label:
var a1 = 1;
`)
);
});
it('label followed by const throws badly', () => {
assert.throws(() => eval(`
label:
const a1 = 1;
`)
);
});
it('label followed by const inside the scope does not throw', () => {
assert.doesNotThrow(() => eval(`
label:
{ const a1 = 1; }
`)
);
});
it('label followed by let inside braces does not throw', () => {
assert.doesNotThrow(() => eval(`
label:{ let a1 = 1 }
`)
);
});
it('a function after a lable throws (spec 13.13.1)', () => {
// https://tc39.github.io/ecma262/#sec-labelled-statements
assert.throws(() => eval(`
label:
function f() {}
`)
);
});
it('a label can not be a number', () => {
assert.throws(() => eval(`
10:
{}
`)
);
});
describe('dynamic labels? (can use variables for labels?)', () => {
it('we cant use variables as labels', () => {
assert.throws(() => eval(`
const x = 'label';
x:
while(true){
continue label;
}
`), SyntaxError);
});
});
it('breaking to a certain label exits the block of the label', () => {
bar: {
while (true) {
break bar;
}
assert(false);
}
});
it('breaking inside a loop of a labeled block only exits the loop', () => {
bar: {
while (true) {
break;
}
assert(true);
return;
}
assert(false, 'It should not get here.');
});
it('`break` breaks out of any number of loops', () => {
bar:
while (true) {
while (true) {
break bar;
}
}
});
it('continue', () => {
let a = 0;
bar:
while (a<1) {
a+= 10;
bar1:
while (a<100) {
continue bar;
}
}
assert.equal(a, 10);
});
xit('succeeds if the label is defined in a while statement', () => {
label1:
{
let a = 0;
while(a < 2) {
label2:
{
a++;
break label1;
}
}
}
// for(var i=0;i<5;i++) {
// let a=0;
// if (a<2) {
// a=a+1;
// continue label1;
// } else {
// assert(false)
// }
// }
});