Created
October 2, 2020 18:23
-
-
Save tudorilisoi/213b7e1d36fda1920ccd1e33fefe0743 to your computer and use it in GitHub Desktop.
Rescursive string splitting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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