Vấn đề
Chúng ta cần viết một hàm JavaScript nằm trên đối tượng prototype của lớp String. Hàm nhận vào một chuỗi phân tách (separator) làm đối số duy nhất (hàm split gốc nhận hai đối số). Hàm sẽ trả về mảng các phần của chuỗi được phân tách bởi separator.
Ví dụ
Dưới đây là mã nguồn:
const str = 'this is some string';
String.prototype.customSplit = (sep = '') => {
const res = [];
let temp = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(el === sep || sep === '' && temp){
res.push(temp);
temp = '';
};
if(el !== sep){
temp += el;
}
};
if(temp){
res.push(temp);
temp = '';
};
return res;
};
console.log(str.customSplit(' '));Kết quả
[ 'this', 'is', 'some', 'string' ]