yangmei yangmei - 1 month ago 7
Javascript Question

type error: object has no method of split

I have been doing an exercise on codewars, however my code passes the tests but it gives a typeError. Couldn't figure out why. Be great if I could get some help... Thanks!

The task is to create a function that can take any string and randomly jumble the letters within each word while leaving the first and last letters of the word in place.

Here's my code:

function shuffle(a) {
var j, x, i;
for (i = a.length; i; i--) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
};

mixwords = function(string){

var array = string.split(" ");

for (var i = 0; i < array.length; i++) {
var itemArray = array[i].split("");
if (itemArray.length > 2) {
var first = itemArray.shift();
var last = itemArray.pop();

shuffle(itemArray);
itemArray.unshift(first);
itemArray.push(last);
var newItem = itemArray.join("");
array[i] = newItem;
}
};
console.log(array.join(" "));
return array.join(" ");
};


The error message goes like this:


TypeError: Object 23 has no method 'split' at mixwords

/runner/frameworks/javascript/cw-2.js:273

throw ex;
^

Answer

You essentially need to sanitize whatever gets passed into the function as the string parameter, in case it's of the Number type.

mixwords = function(string){
  string = typeof string !== 'string' ? string.toString() : string;
  var array = string.split(" ");

  for (var i = 0; i < array.length; i++) {
    var itemArray = array[i].split("");
    if (itemArray.length > 2) {
      var first = itemArray.shift();
      var last = itemArray.pop();

      shuffle(itemArray);
      itemArray.unshift(first);
      itemArray.push(last);
      var newItem = itemArray.join("");
      array[i] = newItem;
    }
  };
  console.log(array.join(" "));
  return array.join(" ");
};

Alternatively, if you need to simply return immediately if a parameter is not a string, this would be the solution:

mixwords = function(string){
  if ( typeof string !== 'string' ) return; // just 'return' to return 'undefined'

  var array = string.split(" ");

  for (var i = 0; i < array.length; i++) {
    var itemArray = array[i].split("");
    if (itemArray.length > 2) {
      var first = itemArray.shift();
      var last = itemArray.pop();

      shuffle(itemArray);
      itemArray.unshift(first);
      itemArray.push(last);
      var newItem = itemArray.join("");
      array[i] = newItem;
    }
  };
  console.log(array.join(" "));
  return array.join(" ");
};