Zig but in JavaScript style

My friend loves JavaScript. I need to make him believe he can use Zig as inefficient as he uses JavaScript. Here is what I came up with:

fn power_of_two (index: u8) !u64 {
    @setEvalBranchQuota(100000);
    switch (index) {
        inline 0...63 => |comptime_value| {
            return comptime std.fmt.parseInt(
                u64,
                "1" ++ "0" ** comptime_value,
                2,
            ) catch unreachable;
        },
        else => return error.IndexOutOfBounds,
    }
}

Who needs << when you can parse strings?

Can the compiler optimize the hell out of this mess? Compiler Explorer

7 Likes

As a js dev, js is becoming a “cancer”, will probably mark futures generations when it’s over

1 Like

Got to love that Zig takes this abomination and turns it into an LUT of u64 constants.

4 Likes

This is absolutely terrific! Good work hahaha

1 Like

You came up with such monstrosity, and i love it!

Tho its not that surprising its mostly optimized out, since comptime happens before LLVM gets its hands on it and at that point its just plain old return precomputed_number; in each switch case.

I am a bit surprised it creates a lookup table instead of shifting, but we cant always get perfect code right?

1 Like