DEV Community

Discussion on: Can you hack this? #3

Collapse
 
_bkeren profile image
'' • Edited
String.prototype.split = function(delimiter, limit) {
  if (this.indexOf(delimiter) < 0) return [this.toString()]

  function splitHelper(str, del, _limit, acc) {

    if (str.length === 0 || limit === _limit) return acc
    if (del.length === 0) return [...str]
    const delIndex = str.indexOf(del)
    if (delIndex < 0) return splitHelper("", del, limit, [...acc, str])
    return splitHelper(str.substring(delIndex + 1), del, _limit + 1, [...acc, str.substring(0, delIndex)])
  }
  return splitHelper(this, delimiter, 0, [])
}

Enter fullscreen mode Exit fullscreen mode