6 kyu

Prefill an Array

9,630 of 13,268user5854572

Description:

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(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) --> [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"
Arrays
Fundamentals

Stats:

CreatedSep 12, 2014
PublishedSep 12, 2014
Warriors Trained23972
Total Skips3675
Total Code Submissions193238
Total Times Completed13268
JavaScript Completions9630
CoffeeScript Completions53
Ruby Completions500
Python Completions3158
Total Stars323
% of votes with a positive feedback rating76% of 1243
Total "Very Satisfied" Votes794
Total "Somewhat Satisfied" Votes300
Total "Not Satisfied" Votes149
Ad
Contributors
  • user5854572 Avatar
  • jhoffner Avatar
  • GiacomoSorbi Avatar
  • siebenschlaefer Avatar
  • Voile Avatar
Ad