Search code examples
javascriptarraysalgorithmfunctioncoding-style

Cleaner way to write this Javascript function


Looking for a better/cleaner/simpler way to write this:

const line1 = 'a string';
const line2 = 'a second string';
const line3 = 'a third string';

  const howManyLinesToRender = (line) => {
   if (line === 1) return [line1];
   if (line === 2) return [line1, line2];
   if (line === 3) return [line1, line2, line3]; 

Solution

  • A simpler way would be to use switch:

    const howManyLinesToRender = (line) => {
       switch (line) {
        case 1: return [line1]
        case 2: return [line1, line2];
        case 3: return [line1, line2, line3];
      }
    }
    

    but as CRice notes in the comments of your question, this very example is satisfiable also by:

    return [line1, line2, line3].slice(0, line)
    

    that is a cleaner oneliner.