-3

I'd like to create a function that I give a number to and it builds me a string of incrementing numbers. I know I can easily accomplish this with a for loop, but is there a cleaner way? Perhaps done in one line (even if it only accomplished the first 2 examples)? Any help is appreciated.

Example:

myFunc(3)
output: $1,$2,$3

myFunc(1)
output: $1

myFunc(0)
output:
MiketheCalamity
  • 1,229
  • 1
  • 15
  • 32
  • 2
    `I know I can easily accomplish this with a for loop` - doesn't look like you do, because you haven't put any code in your question :p - `const myFunc = n => Array.from({length:n}).map((_, i) => '$' + (i+1)).join();` – Jaromanda X Aug 24 '17 at 03:56
  • A for loop can be one line of code. I don't think you can get much cleaner than one line... – Obsidian Age Aug 24 '17 at 03:58
  • https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-an-array-based-on-suppl – sumit Aug 24 '17 at 04:00

3 Answers3

1
var d = function(a) {
    return ((a === 1) ? ("1") : (d(a - 1) + '' + a));
};
user1615664
  • 591
  • 2
  • 11
  • 24
1

You could use the array constructor, fill it with Array.fill and map back the incrementing numbers, like this

function inc(n) {
  return Array(n).fill(0).map((x,i)=>('$'+(i+1)))
}

console.log( inc(4) )

If you want a string, add .join(',') at the end

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • ```function inc(n) {return Array(n).fill(0).map((x, i)=>('$'+(i+1))).join(',')} console.log( inc(4) )``` this works – The Badak Aug 24 '17 at 04:59
1

Seems like a code golf question

f=n=>n<1?'':n>1?f(n-1)+',$'+n:'$1'

console.log(f(3))
console.log(f(1))
console.log(f(0))
Slai
  • 22,144
  • 5
  • 45
  • 53