In Go, I can use a switch
without a condition, and instead provide the conditions in the case
branches, such as:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
(Taken from https://tour.golang.org/flowcontrol/11)
What I like about this approach is that it is much cleaner than if-else if-else if-…
. Unfortunately, this construct is not possible in JavaScript.
How could I create something that looks like this as closely as possible, using some (weird) language constructs?
You can use virtually the same construct as in Go:
var now = new Date();
switch (true) {
case now.getHours() < 12:
console.log('Good morning');
break;
case now.getHours() < 17:
console.log('Good afternoon');
break;
default:
console.log('Good evening');
}
</div>
You could use conditions at the case clause.
var a = 2;
switch (true) { // strict comparison!
case a < 3:
console.log(a + ' is smaller than 3');
break;
}
</div>
abusing the language,
var now = new Date();
now.getHours() < 12 && console.log('Good morning') ||
now.getHours() < 17 && console.log('Good afternoon') ||
now.getHours() >= 17 && console.log('Good evening')