DEV Community


Discussion on: PHP 8 features I wish also existed in JavaScript

wearypossum4770 profile image
Stephen Smith • Edited

I don't follow the link between "native javascript" and typescript. TS is compiled to JS. I think you can use a Map to achieve the same results with a php match. EDIT
This is a haphazardly written code complete with as close to replicated functionality you would expect from PHP match

class UnhandledMatchError extends Error {
    constructor(value, ...args) {
        super(...args) = "UnhandledMatchError"
        this.message = `Unhandled match value of type ${typeof value}`
        Error.captureStackTrace(this, UnhandledMatchError)
const match = item => new Map([
    [100, "Super Thin"],
    [300, "Thin"],
    [400, "Normal"],
    [600, "Bold"],
    [900, "Heavy"]
]).get(item) ?? new UnhandledMatchError(item)

>>> Super Thin
>>> UnhandledMatchError: Unhandled match value of type number
Enter fullscreen mode Exit fullscreen mode
Thread Thread
devmount profile image
Andreas Author

As you already said: TS requires a compiler to JS. This article was meant for those writing JS directly.
Cool idea, can you give an example with Map?