DEV Community

loading...
Cover image for Can you hack this? #3

Can you hack this? #3

Alfredo Salzillo 🐺
🐺
・1 min read

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

Discussion (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
leviathanprogramming profile image
𝐋𝐄𝑽𝐈𝑨𝐓𝐇𝐀𝐍 Programming

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 🐺 Author

I will post more of this then 😊