I came across the following exercise in an OOP book form Packt, and was wondering how other people might approach the solution. I’ve started on mine but feel I might be barking up the wrong tree and not fully understanding the exercise:
Exercise
Imagine the String()
constructor didn’t exist. Create a constructor function, MyString()
, that acts like String()
as closely as possible. You’re not allowed to use any built-in string methods or properties, and remember that String()
doesn’t exist. You can use this code to test your constructor:
> var s = new MyString('hello');
> s.length;
5
> s[0];
"h"
> s.toString();
"hello"
> s.valueOf();
"hello"
> s.charAt(1);
"e"
> s.charAt('2');
"l"
> s.charAt('e');
"h"
> s.concat(' world!');
"hello world!"
> s.slice(1, 3);
"el"
> s.slice(0, -1);
"hell"
> s.split('e');
["h", "llo"]
> s.split('l');
["he", "", "o"]
Note: You can use a for
loop to loop through the input string, treating it as an array.
My current incomplete solution
function MyString(str){
var arr = Array.from(str);
this.length = arr.length;
this.toString = function() {
return arr.join('');
};
this.valueOf = function() {
return arr.join('');
};
this.charAt = function(value) {
value = (!parseInt(value)) ? 0 : parseInt(value);
return arr[value];
};
this.concat = function(value) {
return arr.join('') + value;
};
this.slice = function(start, end) {
var slice = '';
for (var j = start; j < end; j ++){
slice += arr[j];
}
return slice;
};
this.split = function(seperator) {
var split = [];
for (var letter in str){
if (seperator !== str[letter]){
split.push(str[letter]);
}
}
return split;
};
}