freeCodeCamp/curriculum/challenges/spanish/02-javascript-algorithms-an.../basic-algorithm-scripting/repeat-a-string-repeat-a-st...

2.9 KiB

id title localeTitle isRequired challengeType
afcc8d540bea9ea2669306b6 Repeat a String Repeat a String Repetir una cadena Repetir una cadena true 5

Description

Repetir una determinada cadena str (primer argumento) para num veces (segundo argumento). Devuelve una cadena vacía si num no es un número positivo. Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código.

Instructions

Tests

tests:
  - text: &#39; <code>repeatStringNumTimes(&quot;*&quot;, 3)</code> debe devolver <code>&quot;***&quot;</code> .&#39;
    testString: 'assert(repeatStringNumTimes("*", 3) === "***", "<code>repeatStringNumTimes("*", 3)</code> should return <code>"***"</code>.");'
  - text: &#39; <code>repeatStringNumTimes(&quot;abc&quot;, 3)</code> debe devolver <code>&quot;abcabcabc&quot;</code> .&#39;
    testString: 'assert(repeatStringNumTimes("abc", 3) === "abcabcabc", "<code>repeatStringNumTimes("abc", 3)</code> should return <code>"abcabcabc"</code>.");'
  - text: &#39; <code>repeatStringNumTimes(&quot;abc&quot;, 4)</code> debe devolver <code>&quot;abcabcabcabc&quot;</code> .&#39;
    testString: 'assert(repeatStringNumTimes("abc", 4) === "abcabcabcabc", "<code>repeatStringNumTimes("abc", 4)</code> should return <code>"abcabcabcabc"</code>.");'
  - text: &#39; <code>repeatStringNumTimes(&quot;abc&quot;, 1)</code> debe devolver <code>&quot;abc&quot;</code> .&#39;
    testString: 'assert(repeatStringNumTimes("abc", 1) === "abc", "<code>repeatStringNumTimes("abc", 1)</code> should return <code>"abc"</code>.");'
  - text: &#39; <code>repeatStringNumTimes(&quot;*&quot;, 8)</code> debe devolver <code>&quot;********&quot;</code> .&#39;
    testString: 'assert(repeatStringNumTimes("*", 8) === "********", "<code>repeatStringNumTimes("*", 8)</code> should return <code>"********"</code>.");'
  - text: &#39; <code>repeatStringNumTimes(&quot;abc&quot;, -2)</code> debe devolver <code>&quot;&quot;</code> .&#39;
    testString: 'assert(repeatStringNumTimes("abc", -2) === "", "<code>repeatStringNumTimes("abc", -2)</code> should return <code>""</code>.");'
  - text: El método <code>repeat()</code> incorporado no debe utilizarse
    testString: 'assert(!/\.repeat/g.test(code), "The built-in <code>repeat()</code>-method should not be used");'

Challenge Seed

function repeatStringNumTimes(str, num) {
  // repeat after me
  return str;
}

repeatStringNumTimes("abc", 3);

Solution

function repeatStringNumTimes(str, num) {
  if (num < 0) return ";
  return num === 1 ? str : str + repeatStringNumTimes(str, num-1);
}

repeatStringNumTimes("abc", 3);