Created
April 15, 2021 19:20
-
-
Save kraftdorian/39ed6bba7c5feb703e1d4068ed9f52a9 to your computer and use it in GitHub Desktop.
Recursive string split in JavaScript written in Erlang style
This file contains hidden or 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
const usePrologStyleList = (array) => { | |
const [head, ...tail] = array; | |
return [head, tail]; | |
}; | |
const useErlangStyleString = (string, resultString) => { | |
const length = string.length; | |
if (!length) { | |
return resultString; | |
} | |
return useErlangStyleString(string.substr(0, length - 1), [string.charCodeAt(length - 1)].concat(resultString)); | |
}; | |
const splitString = (string, separator, words, acc) => { | |
const [head, tail] = usePrologStyleList(string); | |
if (head === undefined) { | |
return words.concat([acc]).map(word => String.fromCharCode(...word)); | |
} | |
if (head === separator) { | |
return splitString(tail, separator, words.concat([acc]), []); | |
} else { | |
return splitString(tail, separator, words, acc.concat(head)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use case:
Result: