Chainable switch case class
Chainable switch case class
by Csaba Hellinger
JavaScript
class Switch {
constructor (defaultValue) {
this.defaultValue = defaultValue;
this.found = false;
this.value = undefined;
}
case(condition, value) {
if (!this.found && condition) {
this.value = value;
this.found = true;
}
return this;
}
result() {
return this.found ? this.value : this.defaultValue;
}
}
// --------
const isA = false;
const isB = true;
const isC = true;
const result = new Switch('icon-default')
.case(isA, 'icon-a')
.case(isB, 'icon-b')
.case(isC, 'icon-c')
.result();
document.body.innerText = result;