Implement Split method with a function

1.3k views Asked by At

I want to implement the split method with a function

This is what i am trying to achieve

var string = 'aa,bb,c';

var separator = ',';

var stringList = string.split(separator);

function splitString() {
  console.log(stringList);
}

This returns this array  

["aa", "bb", "c"]

I am trying to implement the same with a function but it returns an empty array [] and not ["aa", "bb", "c"]

I have created a jsbin for who can help out.

function split(string,separator) {
  var cache = [];
  var cachInt = 0;
  var lastWord = '';
  for (var i = 0; i < string.length; i++) {
    if(string[i] === separator) {
        cachInt++
        lastWord = ''
    }
    else {
      lastWord = lastWord + string[i];
      cache[cachInt] == lastWord;
    }
  }
  return cache;
}


function splitString() {
  console.log(split('string, separator',','));
}
1

There are 1 answers

0
Martijn On

You do this:

cache[cachInt] == lastWord;

Which should be, because you're not comparing, you're assigning:

cache[cachInt] = lastWord;

While we're at it, there is room for improvement. Your version has the line mentioned above. That line gets run every iteration of i. Thats not really needed, as you only want to perform a save on a split:

if(string[i] === separator) {
    cache[cachInt] = lastWord; // Only assign when we find a seperator
    cachInt++
    lastWord = ''
} else {
    lastWord = lastWord + string[i];
}

This has a tiny issue: The last part of string often doesn't have the seperator, it's a,b,c and not a,b,c,. We can fix that easily with a check after the for to see if you have anything remaining:

if( lastWord!=='' ){
     cache[cachInt] = lastWord;
}
return cache;

This has the added feature that it works as a rtrim() (wether you want that or not is up to you to fix).

Also, if you don't need to support older IE versions, then don't use var, use let. If you want to know why, this question explains it well.


Then, you're using a counter to remember which cachInt to use. As we now only use it once per "cacheInt", eg once per word, we know that each addition is +1, and only happens once per word. We also don't really care about the index, we just want each word to be added once. So, you can do cache[] = lastWord, or use push, which is slightly neater: cache.push(lastWord).
By removing the use for this counter, you can also remove the cachInt++ and the let/var cachInt at the beginning of the function, resulting in smaller code.

Result of all of the above:

https://jsbin.com/mejayuv/1/edit?html,js,console,output