tanrax / soy-un-buen-programador-js

Juego con retos sencillos de JavaScript para probarte a ti mismo que sabes lo que haces
11 stars 2 forks source link

Challenge 7 #29

Open nestor-almarza opened 2 years ago

nestor-almarza commented 2 years ago
  /**
   * 
   * @param {Integer} howLongWeWantTheArray 
   * @param {Integer} highest 
   * @param {Integer} lowest 
   * @returns {Array} distinct ordered ascendant
   */      
  const getOrderedDistinctArray = (howLongWeWantTheArray = 5, highest = 10, lowest = 1 ) => {
    // Restraint on input type
   const inputs = [howLongWeWantTheArray, highest, lowest];
   if( inputs.some( input => !Number.isInteger(input) )){ throw "All inputs must be Integers." };

    // We subtract 1 to make it the input more natural
    const minimun = lowest - 1 ;
    // Restraint in case there's not enough values within the given parameters
    if( howLongWeWantTheArray > ( highest - minimun )){ throw "This could create an infinite loop."};
    // generates a random integer according to input limitations 
    const generateRandomNumber = () => ( Math.ceil(Math.random() * ( highest - minimun ))) + minimun ;
    // Adds a unique value in the array
    function addDistinctElementInArray(array){
      const suitor = generateRandomNumber();
      return (array.includes(suitor)) ? addDistinctElementInArray(array) : suitor ;
    }
    // Adds integers until the howLongWeWantTheArray condition is satisfied
    function repeat(array){
      return  ( array.length > howLongWeWantTheArray - 1 ) 
      ? array
      : repeat([...array, addDistinctElementInArray(array)]);
    }
    // Sorts the values in ascending order
    return repeat([]).sort( (currentElement, nextElement) => currentElement - nextElement );
  }

  console.log(getOrderedDistinctArray())
tanrax commented 2 years ago

@nestor-almarza Muy interesante, me gusta como lo has resuelto. Además, está ordenado, comentado y es fácil de añadir cambios. Buen trabajo.