Skip to content

Instantly share code, notes, and snippets.

@Mehuge
Created June 21, 2018 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mehuge/f82eefb9b52dc4b1e9cfba2710c8c3ed to your computer and use it in GitHub Desktop.
Save Mehuge/f82eefb9b52dc4b1e9cfba2710c8c3ed to your computer and use it in GitHub Desktop.
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
function startsWith(string, target, position) {
const { length } = string
position = position || 0
target = `${target}`
return string.slice(position, position + target.length) == target
}
export default startsWith
@Mehuge
Copy link
Author

Mehuge commented Jun 21, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment