Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 4.85 KB

43-prefill-an-array.md

File metadata and controls

57 lines (40 loc) · 4.85 KB

Problem:

Create the function prefill that returns an array of n elements that all have the same value v. See if you can do this without using a loop.

You have to validate input:

  • v can be anything (primitive or otherwise)
  • if v is ommited, fill the array with undefined
  • if n is 0, return an empty array
  • if n is anything other than an integer or integer-formatted string (e.g. '123') that is >=0, throw a TypeError

When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.

Code Examples

    prefill(3,1) --> [1,1,1]
prefill(<span class="hljs-number">2</span>,<span class="hljs-string">&quot;abc&quot;</span>) --&gt; [<span class="hljs-string">&apos;abc&apos;</span>,<span class="hljs-string">&apos;abc&apos;</span>]

prefill(<span class="hljs-string">&quot;1&quot;</span>, <span class="hljs-number">1</span>) --&gt; [<span class="hljs-number">1</span>]

prefill(<span class="hljs-number">3</span>, prefill(<span class="hljs-number">2</span>,<span class="hljs-string">&apos;2d&apos;</span>))
  --&gt; [[<span class="hljs-string">&apos;2d&apos;</span>,<span class="hljs-string">&apos;2d&apos;</span>],[<span class="hljs-string">&apos;2d&apos;</span>,<span class="hljs-string">&apos;2d&apos;</span>],[<span class="hljs-string">&apos;2d&apos;</span>,<span class="hljs-string">&apos;2d&apos;</span>]]

prefill(<span class="hljs-string">&quot;xyz&quot;</span>, <span class="hljs-number">1</span>)
  --&gt; throws <span class="hljs-built_in">TypeError</span> <span class="hljs-keyword">with</span> message <span class="hljs-string">&quot;xyz is invalid&quot;</span></code></pre>
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"
    prefill 3, 1 #returns [1, 1, 1]

    prefill 2, "abc" #returns ["abc","abc"]

    prefill "1", 1 #returns [1]

    prefill 3, prefill(2, "2d")
      #returns [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill "xyz", 1
      #throws TypeError with message "xyz is invalid"

Solution