lessel132
lessel132

Reputation: 41

Trying to write a javascript function that counts to the number inputted

Trying to take an integer and have it return as a
string with the integers from 1 to the number passed. Trying to use a loop to return the string but not sure how!

Example of how I want it to look:

count(5)    =>  1,  2,  3,  4,  5
count(3)    =>  1,  2,  3

Not really sure where to even start

Upvotes: 3

Views: 1330

Answers (6)

John Hascall
John Hascall

Reputation: 9416

Quite possibly the most ridiculous way, defining an iterator:

"use strict";

function count ( i ) {
  let n = 0;
  let I = {};
  I[Symbol.iterator] = function() {
     return { next: function() { return (n > i) ? {done:true}
                                                : {done:false, value:n++} } } };
  let s = "";
  let c = "";
  for ( let i of I ) {
      s += c + i;
      c = ", "
  }
  return s;
}


let s = count(3);
console.log(s);

Upvotes: 0

chiliNUT
chiliNUT

Reputation: 19573

here is a goofy way to do it

function count(i)
{
    while (i--) {
        out = (i + 1) + "," + this.out;
    }
    return (out + ((delete out) && "")).replace(",undefined", "");
}

Upvotes: 0

jib
jib

Reputation: 42450

Here's a non-recursive solution:

var sequence = num => new Array(num).fill(0).map((e, i) => i + 1).toString();

Upvotes: 0

MinusFour
MinusFour

Reputation: 14423

I would do it with a recursive function. Keep concatenating the numbers until it reaches 1.

var sequence = function(num){
    if(num === 1) return '1';
    return sequence(num - 1) + ', ' + num;
}

Or just:

var sequence = (num) => num === 1 ? '1' : sequence(num - 1) + ', ' + num;

Upvotes: 7

AMACB
AMACB

Reputation: 1298

Try this:

function count(n) {
    var arr = [];
    for (var i = 1; i<=n; i++) {
        arr.push(i.toString());
    }
    return arr.toString();
}

Upvotes: 0

Jonathan.Brink
Jonathan.Brink

Reputation: 25403

You can use a for loop to iterate the number of times that you pass in. Then, you need an if-statement to handle the comma (since you don't want a comma at the end of the string).

function count(num) {
  var s = "";
  for(var i = 1; i <= num; i++) {
    s += i;

    if (i < (num)) {
      s += ', ';
    }
  }
  return s;
}

JSBin

Upvotes: 1

Related Questions