OOP - chapter 4 - string
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:
by creativevilla
September 16, 2013
JavaScript
function MyString(strOrg) {
str = strOrg.split('');
//this[0] = str[0];
this.name = str.join('');
this.length = str.length;
this.toString = function () {
return str.join('');
};
this.valueOf = function () {
return str.join('');
};
this.charAt = function (index) {
if (parseInt(index, 10)) {
return strOrg[index];
} else {
return strOrg[0];
}
};
this.concat = function (newStr) {
return strOrg + newStr;
};
this.slice = function (p1, p2) {
var sliced = [];
if (p2 < 0) {
p2 = str.length + p2;
for (var i = p1; i < p2; i++) {
sliced[i] = str[i];
}
return sliced.join('');
} else {
for (var j = p1; j < p2; j++) {
sliced[j] = str[j];
}
return sliced.join('');
}
};
this.reverse = function () {
return str.reverse().join("");
};
return this;
}
var s = new MyString('hello');
console.log(s.length); // 5
console.log(s.toString()); // hello
console.log(s.valueOf()); // hello
console.log(s[0]); // undefined
console.log(s.charAt(1)); // e
console.log(s.charAt('2')); // l
console.log(s.charAt('e')); // h
console.log(s.concat(' world!')); // hello world!
console.log(s.slice(1, 3));
console.log(s.slice(0, -1));
console.log(s.reverse());