I have this string
\'john smith~123 Street~Apt 4~New York~NY~12345\'
Using JavaScript, what is the fastest way to parse this into
This string.split("~")[0];
gets things done.
source: String.prototype.split()
Another functional approach using curry and function composition.
So the first thing would be the split function. We want to make this "john smith~123 Street~Apt 4~New York~NY~12345"
into this ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');
So now we can use our specialized splitByTilde
function. Example:
splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
To get the first element we can use the list[0]
operator. Let's build a first
function:
const first = (list) => list[0];
The algorithm is: split by the colon and then get the first element of the given list. So we can compose those functions to build our final getName
function. Building a compose
function with reduce
:
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
And now using it to compose splitByTilde
and first
functions.
const getName = compose(first, splitByTilde);
let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"