samedi 8 août 2020

Pick random value from object property using Math.random WITHOUT arrays, cycles, Object.keys and additional libraries, frameworks

I have got a task that I described in title. I MUST NOT to use arrays, cycles and Object.keys somewhere in my code. I can only use Math.random.

Actually this must be JSON object, but it’ll be ok if I write work with simple object in javascript.

I can't even imagine how to do this without technologies that i described. If the task supported Object.keys it will be very simple (but i can't write this as answer).

Object:

let obj = {
           key: "item 1, item 2, item 3",
           key2: "abc",
           key3: "123"
       };

My function to pick random value with Object.keys (that i can't use):

 let randomProperty = function (obj) { 
 let keys = Object.keys(obj);    
 return obj[keys[ keys.length * Math.random() << 0]]; 
};

Please help!




Aucun commentaire:

Enregistrer un commentaire