This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function startsWith(string, target, position) { | |
debugger; | |
const { length } = string | |
position = position == null ? 0 : position | |
if (position < 0) { | |
position = 0 | |
} | |
else if (position > length) { | |
position = length | |
} | |
target = `${target}` | |
return string.slice(position, position + target.length) == target | |
} | |
export default startsWith |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function startsWith(string, target, position) { | |
const { length } = string | |
position = position || 0 | |
target = `${target}` | |
return string.slice(position, position + target.length) == target | |
} | |
export default startsWith |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
startsWith('efg', 'h', 4) should return false
startsWith('efg', 'd', -1) should return false
startsWith('efg', '', 4) should return true
startsWith('efg', '', -1) should return true
Both versions do this, buy my version removes redundant code and save space.
position = position == null ? 0 : position
can be expressed as
position = position || 0
because if position is null or undefined or false, 0 is used else position
startsWith('abc','a') should return true
if (position < 0) {
position = 0
}
else if (position > length) {
position = length
}
can be dropped because
target = 'a'
'abc'.slice(-1,-1+target.length) == ''
'abc'.slice(4,4+target.length) == ''
so the bounds check is redundant.