LingDong- / q5xjs

A small and fast alternative (experimental) implementation of p5.js
https://q5xjs.netlify.app/
The Unlicense
544 stars 25 forks source link

random function with no args #4

Closed EricRovell closed 3 years ago

EricRovell commented 3 years ago

I was experimenting with the library and stumbled upon random function that was not working without arguments. According to p5js version it should return a pseudo-random value between [0, 1).

p5js random function reference

Not the function checks if it is a number or an array and if it not any of it, returns the random value in range [0, 1).

LingDong- commented 3 years ago

Hi @EricRovell, thanks a lot for the PR!

I had to change your solution a little bit, so I directly pushed to master: 011d35c3c9a70df4a50153bb84ad98490c68852f

$.random = function(a,b){
  if (a == undefined){
    return rng1.rand();
  }
  if (typeof a == 'number'){
    if (b != undefined){
      return rng1.rand()*(b-a)+a;
    }else{
      return rng1.rand()*a;
    }
  }else{
    return a[~~(a.length*rng1.rand())];
  }
}

Thanks!

EricRovell commented 3 years ago

Always glad to help :)

The only thing I am concerned, if user passes an object, for example, it will not work. Object has no length property, and your else clause works as if the parameter is an array. Personally, I think, it is still better to check if it is an array and just return random [0, 1) value in case of invalid input too.

LingDong- commented 3 years ago

Yup you're totally right that the array check is a better in that sense -- but q5's philosophy is that the user should fix their code to provide valid input, instead of relying on the library to hide their mistakes :) https://github.com/LingDong-/q5xjs#iii-hes-