• 0 Posts
  • 8 Comments
Joined 1 year ago
cake
Cake day: July 2nd, 2025

help-circle
  • I was thinking of the three legal states as:

    • not logged in (null or {isAdmin: false, isLoggedIn: false})
    • logged in as non-admin (false or {isAdmin: false, isLoggedIn: true})
    • logged in as admin (true or {isAdmin: true, isLoggedIn: true})

    which leaves {isAdmin: true, isLoggedIn: false} as an invalid, nonsensical state. (How would you know the user’s an admin if they’re not logged in?) Of course, in a different context, all four states could potentially be distinctly meaningful.


  • My preferred way of modelling this would probably be something like
    role: "admin" | "regular" | "logged-out"
    or
    type Role = "admin" | "regular";
    role: Role | null
    depending on whether being logged out is a state on the same level as being a logged-in (non-)admin. In a language like Rust,
    enum Role {Admin, Regular}
    instead of just using strings.

    I wouldn’t consider performance here unless it clearly mattered, certainly not enough to use
    role: number,
    which is just about the least type-safe solution possible. Perhaps
    role: typeof ADMIN | typeof REGULAR | typeof LOGGED_OUT
    with appropriately defined constants might be okay, though.

    Disclaimer: neither a professional programmer nor someone who regularly writes TypeScript as of now.






  • Can’t resist pointing out how you should actually write the function in a “real” scenario (but still not handling errors properly), in case anyone wants to know.

    If the list is guaranteed to have exactly two elements:

    fn is_second_num_positive_exact(input: &str) -> bool {
        let (_, n) = input.split_once(',').unwrap();
        n.parse::<i32>().unwrap() > 0
    }
    

    If you want to test the last element:

    fn is_last_num_positive(input: &str) -> bool {
        let n = input.split(',').next_back().unwrap();
        n.parse::<i32>().unwrap() > 0
    }
    

    If you want to test the 2nd (1-indexed) element:

    fn is_second_num_positive(input: &str) -> bool {
        let n = input.split(',').nth(1).unwrap();
        n.parse::<i32>().unwrap() > 0
    }