Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Created April 15, 2021 19:20
Show Gist options
  • Save kraftdorian/39ed6bba7c5feb703e1d4068ed9f52a9 to your computer and use it in GitHub Desktop.
Save kraftdorian/39ed6bba7c5feb703e1d4068ed9f52a9 to your computer and use it in GitHub Desktop.
Recursive string split in JavaScript written in Erlang style
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));
}
};
@kraftdorian
Copy link
Author

Use case:

const string = useErlangStyleString('Erlang is fun!', []);
const result = splitString(string, ' '.charCodeAt(0), [], []);
console.log(result);

Result:

[ 'Erlang', 'is', 'fun!' ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment