Skip to content

Instantly share code, notes, and snippets.

@UniBreakfast
Created July 18, 2022 08:47
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 UniBreakfast/0886e4197092e54434a2408e0c65856f to your computer and use it in GitHub Desktop.
Save UniBreakfast/0886e4197092e54434a2408e0c65856f to your computer and use it in GitHub Desktop.
String.prototype.split_ = function (sep, limit = this.length) {
if (sep === undefined) return [String(this)]
if (limit === Infinity) return []
const parts = [], length = this.length, len = sep.length
const isSepStart = i => {
for (let j = 0; j < len; j++) {
if (this[i + j] != sep[j]) return false
}
return true
}
for (let i = 0; i <= length && parts.length < limit; i++) {
let part = ''
while (i < length && !isSepStart(i)) part += this[i++]
if (len) i += len - 1
else part = this[i]
if (part !== undefined) parts[parts.length] = part
}
return parts
}
results = ([
{
str: 'a bc def',
split: 'a bc def'.split(),
split_: 'a bc def'.split_(),
},
{
str: 'a bc def', substr: ' ',
split: 'a bc def'.split(' '),
split_: 'a bc def'.split_(' '),
},
{
str: ' a bc def ', substr: ' ',
split: ' a bc def '.split(' '),
split_: ' a bc def '.split_(' '),
},
{
str: 'a - bc - def', substr: ' - ',
split: 'a - bc - def'.split(' - '),
split_: 'a - bc - def'.split_(' - '),
},
{
str: 'a bc def', substr: '',
split: 'a bc def'.split(''),
split_: 'a bc def'.split_(''),
},
{
str: 'a bc def', substr: '', limit: 1,
split: 'a bc def'.split('', 1),
split_: 'a bc def'.split_('', 1),
},
{
str: 'a bc def', substr: '', limit: 4,
split: 'a bc def'.split('', 4),
split_: 'a bc def'.split_('', 4),
},
{
str: 'a bc def', substr: '', limit: 99,
split: 'a bc def'.split('', 99),
split_: 'a bc def'.split_('', 99),
},
{
str: 'a bc def', substr: '', limit: Infinity,
split: 'a bc def'.split('', Infinity),
split_: 'a bc def'.split_('', Infinity),
},
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment