Unique array of random numbers using functional programming -


i'm trying write code in functional paradigm practice. there 1 case i'm having problems wrapping head around. trying create array of 5 unique integers 1, 100. have been able solve without using functional programming:

let uniquearray = [];  while (uniquearray.length< 5) {   const newnumber = getrandom1to100();   if (uniquearray.indexof(newnumber) < 0) {     uniquearray.push(newnumber)   } } 

i have access lodash can use that. thinking along lines of:

const uniquearray = [   getrandom1to100(),    getrandom1to100(),    getrandom1to100(),    getrandom1to100(),    getrandom1to100() ].map((currentval, index, array) => {       return array.indexof(currentval) > -1 ? getrandom1to100 : currentval;     }); 

but wouldn't work because return true because index going in array (with more work remove defect) more importantly doesn't check second time values unique. however, i'm not quite sure how functionaly mimic while loop.

how's this:

const addunique = (ar) => {     const el = getrandom1to100();     return ar.includes(el) ? ar : ar.concat([el]) }  const uniquearray = (numberofelements, basearray) => {     if (numberofelements < basearray.length) throw 'invalid input'      return basearray.length === numberofelements ? basearray : uniquearray(numberofelements, addunique(basearray)) } const myarray = uniquearray(5, []) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -