Im trying create my own substring method in JS
function substr(string, p1 = 0, p2 = string.length) {
if (string.length === 0 || p2 < 0 || p1 > p2) return '';
const p11 = p1 <= 0 ? 0 : p1
let p22 = p2 > string.length ? string.length : p2
const str = string.split('').reduce((acc, item, i) => {
if (i >= p11 && i < p22) {
console.log('i:', i)
return acc.concat(item)
}
return acc
}, '');
console.log('inside', str)
return str
}
when Im test this code I have an error
expect(substr('abba', 1, 0)).toEqual(''); // pass
expect(substr('abba', 0, 1)).toEqual('a'); // pass
expect(substr('abba', 0, 1)).toEqual('a'); // pass
expect(substr('abba', 1, 2)).toEqual('bb'); // failed
How I can fix my code to pass tests?
return string.slice(p1, p2)slice.sliceor any thing similar is probably considered "cheating" as it would greatly simplify the code.p2supposed to be the length of the substring, or the final (excluded) position?splitandconcat, so what difference couldslicepossibly make?