DEV Community

Cover image for Can you hack this? #3
Alfredo Salzillo
Alfredo Salzillo

Posted on

Can you hack this? #3

Can you implement the String.prototype.split without using while, for, and other imperative cycles?

Top comments (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
Collapse
 
ironcladdev profile image
Conner Ow

Man, these are so fun!! You gotta post these more often.
I am dead at this problem. I got as far as splitting the string into an array with [...string] but my brain broke after that.

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

I will post more of this then 😊