arrays - Emulate string split() from Javascript Object Oriented Programing Stoyan Stefanov book -
arrays - Emulate string split() from Javascript Object Oriented Programing Stoyan Stefanov book -
im learning js oop stoyan stefanov's book. got problem exercise 4 in chapter 4:
imagine string()constructor didn't exist. create constructor function mystring()that acts string()as closely possible. you're not allowed utilize built-in string methods or properties, , remember string()doesn't exist. can utilize code test constructor:
below effort creating string split() method. guide me how create work ?
class="snippet-code-js lang-js prettyprint-override">function minestring(string){ this.lengths = string.length; //this[1] = "test"; for(var = 0; < string.length;i++){ this[i] = string.charat(i); } this.tostring = function(){ homecoming string; } this.split = function(char){ var splitedarray = []; var foundedchar = []; var string2 = []; (var = 0; < this.lengths ; i++){ foundedchar.push(string[i].indexof(char)); } (var j = 0; j < foundedchar.length; j++){ if(foundedchar[j] === -1){ //splitedarray[0] += string.charat(j); //splitedarray[j] = string.charat(j); string2 += string.charat(j); //splitedarray.push(string2); splitedarray[foundedchar.length] = string2; }else if (foundedchar[j] === 0){ //splitedarray.push(string.charat(j)); } } homecoming splitedarray; } } var text = new minestring("hello"); text.split("e");
so text.split("e"); should display this:
class="snippet-code-js lang-js prettyprint-override">var text = new minestring("hello"); text.split("e"); ["h","llo"]
your split method looks somehow overly complicated. simplified , rewrote other parts of class adhere task of not using string methods. see jsfiddle or code below.
new js-code:
function minestring(str){ this.str = str; this.addchar = function(c) { this.str += c; } this.length = function() { homecoming this.str.length; } this.tostring = function(){ homecoming this.str; } this.split = function(char){ var out = [], current = new minestring(""), addcurrent = function() { if (current.length() > 0) { out.push(current.tostring()); current = new minestring(""); } }; (i = 0; < this.str.length; i++) { if (this.str[i] == char) { addcurrent(); } else { current.addchar(this.str[i]); } } addcurrent(); homecoming out; } } var text = new minestring("hello"); console.log(text.split("e"));
outputs:
["h", "llo"]
javascript arrays string oop
Comments
Post a Comment