I am reading "Object-Oriented JavaScript" by Stoyan Stefanov to learn JavaScript and in the end of the chapter named "Objects", there's an exercise that asks you to implement your own String
object. I have implemented some methods of String
(not all), I'd be happy if you could check and let me know how it could be done better:
function MyString(primitive) {
this.length = 0;
var i = 0;
// Here length is calculated and the indexer is set.
for (var c in primitive) {
this[i++] = primitive[c];
this.length++;
}
this.toString = function() { return primitive; };
this.valueOf = this.toString;
this.substring = function(start, end) {
var result = '';
// Edge cases for the parameters.
if ((typeof end !== 'number' && typeof parseInt(end) !== 'number') || end > this.length)
end = this.length;
if (end <= 0 || isNaN(end)) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
result += this[i];
}
return result;
}
this.charAt = function(i) {
var x = parseInt(i);
x = isNaN(x) ? 0 : x;
return this.substring(x, x+1);
};
return this;
}
var s = new MyString('hello');
console.log(s.length);
console.log(s[0]);
console.log(s.toString());
console.log(s.valueOf());
console.log(s.charAt(1));
console.log(s.charAt('2'));
console.log(s.charAt('e'));
console.log(s.substring(1, 3));
Any and all suggestions are welcome. I'm completely new to JavaScript and would love to hear my mistakes.