Code Wars: Salesman's Travel
A traveling salesman has to visit clients. He got each client's address e.g.
"432 Main Long Road St. Louisville OH 43071"
as a list.
The basic zipcode format usually consists of two capital letters followed by a white space and five digits. The list of clients to visit was given as a string of all addresses, each separated from the others by a comma, e.g. :
"123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"
.
To ease his travel he wants to group the list by zipcode.
Task
The function
travel
will take two parameters r
(addresses' list of all clients' as a string) and zipcode
and returns a string in the following format:zipcode:street and town,street and town,.../house number,house number,...
The street numbers must be in the same order as the streets where they belong.
If a given zipcode doesn't exist in the list of clients' addresses return
"zipcode:/"
Pseudocode: Split up the string and save into 3 different variables. From there, concatenate the 3 variables according to the format they want the string in.
function travel(r, zipcode) {
let arr = r.split(",");
let letterArr = [];
let numArr;
let regex = /\d{5}/;
if (!arr.find(item => item.includes(zipcode)) || !regex.test(zipcode)) {
return zipcode + ":/";
}
arr = arr.filter(item => item.includes(zipcode));
arr = arr.map(item => item.substr(0, item.indexOf(zipcode)));
for (i = 0; i < arr.length; i++) {
if (arr[i].match(/[a-z.]+/gi) !== null) {
letterArr.push(arr[i].match(/[a-z.]+/gi).join(" "));
}
}
numArr = arr.map(item => item.match(/[0-9]+/g));
return zipcode + ":" + letterArr.join(",") + "/" + numArr.join(",");
}
Comments
Post a Comment