1

I am trying to come up with a function that will take any string and output an array of numbers and strings without using .split(). Below are the tests it needs to pass and a function that passes the tests currently. I am curious about how other people would solve this.

function csvParse(inputString) {
   var outputArray = [];
   var inputArray = inputString.split(',');
   for (var i =0; i < inputArray.length; i++) {
     if (!Number.isNaN(+inputArray[i])) {
       outputArray.push(+inputArray[i]);
   } else {
     outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
   }
   }
   return outputArray;
};

describe('CSV Parse', function() {
  it('should parse a string of integers correctly', function() {
    var input = '3,7,9,1,25';
    var output = [ 3, 7, 9, 1, 25 ];
    expect(csvParse(input)).to.deep.equal(output);
  });
  it('should parse a string of strings correctly', function() {
    var input = '"3","7","9","1","25"';
    var output = ["3", "7", "9", "1", "25"];
    expect(csvParse(input)).to.deep.equal(output);
  });
  it('should parse a string of integers and strings correctly', function() {
    var input = '1, "one", 2, "two", 3, "three"';
    var output = [1, "one", 2, "two", 3, "three"];
    expect(csvParse(input)).to.deep.equal(output);
  });
});
4
  • 3
    I would solve it by using split. If a language feature is present, why not use it rather than rolling your own, very likely broken, implementation? Commented Nov 18, 2015 at 17:12
  • Do not reinvent the wheel... :) Commented Nov 18, 2015 at 17:14
  • Sounds like an assignment. If you don't do it yourself, how will you explain why you made the decisions in your code? Commented Nov 18, 2015 at 17:14
  • To parse CSV use a dedicated library, e.g. github.com/wdavidw/node-csv Commented Nov 18, 2015 at 17:16

2 Answers 2

2

Basic JS solution just replacing the split method as you asked (fiddle here)

function dumbComaSplit(inputString) {
   var strArray = [];
   var tmpStr = "";
   for (var i = 0; i < inputString.length; i++) {
        if (inputString.charAt(i) == ',') {
            strArray.push(tmpStr);
            tmpStr = "";
            continue;
        }
        tmpStr += inputString.charAt(i);
    }
    strArray.push(tmpStr);
    return strArray;
};

function csvParse(inputString) {
   var outputArray = [];
   var inputArray = dumbComaSplit(inputString);
   for (var i =0; i < inputArray.length; i++) {
     if (!Number.isNaN(+inputArray[i])) {
       outputArray.push(+inputArray[i]);
   } else {
     outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
   }
   }
   return outputArray;
};
Sign up to request clarification or add additional context in comments.

Comments

1

If you really really want to parse CSV format without spilt, here is one way you can do it using new ECMAScript 6 Template Strings feature.

The basic is that we replace CSV , with mock ${b} expressions and convert the string to a Template String. Then evaluate it while using tag feature. This will create the array for us.

Here is the fiddle.

function csvParse(inputString) {

     b = null;       //dummy variable

     //Prepare the notation to be a TemplateString. Use var b in a dummy expression
     inputString = "`" + inputString.replace(/,/g, '${b}') + "`";


     //Evaluate. Note that we use a tag function inside the evaluation to create the array
     //We also pass the string as a  Template String to evaluate. This is optional
     fn = new Function(`function tag(inputArray) {
                           return inputArray;
                        } 

                        return tag  ${inputString}  `);


     //Return the array         
     return fn().raw;

};


console.log(csvParse("power,of,es6")); 

split is the way to go. But this is the answer you are looking for.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.