Skip to content

Instantly share code, notes, and snippets.

@tudorilisoi
Created October 2, 2020 18:23
Show Gist options
  • Save tudorilisoi/213b7e1d36fda1920ccd1e33fefe0743 to your computer and use it in GitHub Desktop.
Save tudorilisoi/213b7e1d36fda1920ccd1e33fefe0743 to your computer and use it in GitHub Desktop.
Rescursive string splitting
/*
Write a recursive function that splits a string based on a separator (similar to String.prototype.split).
Don't use JS array's split function to solve this problem.
Input: 02/20/2020
Output: ["02", "20", "2020"]
https://courses.thinkful.com/dsa-v1/checkpoint/2
*/
function splitString(str, sep) {
const foundIndex = str.indexOf(sep)
if (foundIndex === -1) {
return [str]
}
const piece = str.substring(0, foundIndex)
const remaining = str.substring(foundIndex+1)
console.log(`str: ${str}, index: ${foundIndex}, remaining: ${remaining}`)
const remainingResult = splitString(remaining, sep)
// return [piece].concat(remainingResult)
return [piece, ...remainingResult]
}
const result = splitString('123/45678/abcde', '/')
console.log(`result`, result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment