• Admiral Patrick@dubvee.org
    link
    fedilink
    English
    arrow-up
    41
    ·
    edit-2
    15 days ago

    Hey, I like a little chaos in my codebase 😆

    const funsies = () => (Math.round(Math.random() * 1000) % 2 == 0)
    if ( condition || funsies() ) {
        // do the thing
    }
    
    • sorrybookbroke@sh.itjust.works
      link
      fedilink
      English
      arrow-up
      6
      ·
      edit-2
      14 days ago

      Wait, why the the *1000 or mod 2? Won’t that give a 50\50 chance or the same as Math.round(Math.random).

      No shade, and I may be wrong myself I am very tired

      • mexicancartel@lemmy.dbzer0.com
        link
        fedilink
        English
        arrow-up
        2
        ·
        14 days ago

        Probably to make the fractional random value between 0 and 1 to become an integer so that you can divisibility check for even with mod 2

      • Admiral Patrick@dubvee.org
        link
        fedilink
        English
        arrow-up
        19
        ·
        edit-2
        15 days ago

        Nope. I’m staunchly against “AI”. If the code sucks, it’s because I wrote bad code.

        Edit: Oh, or did you mean is that how “AI” works?

      • Admiral Patrick@dubvee.org
        link
        fedilink
        English
        arrow-up
        3
        ·
        edit-2
        15 days ago

        In Javascript, Math.random() produces a float value between 0 and 1, so I multiply by 1000 and round it to get a larger integer. The value %2 == 0 is a non-library way of performing isEven() on the random integer (value % 2 is 0 if even, 1 if odd, and the ==0 makes it return a boolean). When used in the if statement, it’s essentially a coin flip.

        • juliebean@lemm.ee
          link
          fedilink
          English
          arrow-up
          3
          ·
          10 days ago

          does javascript not allow you to interpret integers as booleans in a conditions directly? seems it’d be simpler to just do math.round(math.random()), which should still get you true (1) or false (0) in equal likelihood. or am i missing something?

          • Admiral Patrick@dubvee.org
            link
            fedilink
            English
            arrow-up
            1
            ·
            edit-2
            10 days ago

            It’ll give you 1 ~= true or 0 ~= undefined, but I typically use Typescript which prefers actual booleans to boolean-ish

            • juliebean@lemm.ee
              link
              fedilink
              English
              arrow-up
              1
              ·
              10 days ago

              huh. interesting. i wonder what number it’s actually storing for false then?