Friday, 4 December 2015

Kata Day 10: Format String


Problem Description: Given: an array containing hashes of names

Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.

Example:
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'

list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'

list([ {name: 'Bart'} ])
// returns 'Bart'

list([])
// returns ''

Level: 6kyu

Link to Kata: Format String

Our first aim while solving this Kata should be to extract all the names corresponding to hashes in a single array. We create an empty output array and push all the names into it while looping through the given array.

We create an empty string called "ans". If the length of output array is 1 then we put answer equal to first and only element of output array and return the answer. If the length is greater than 1 then we loop through all the elements of output array and add every element to ans variable followed by a comma and a star. We keep a check on looping index and if it points to the second last element of output array then we add the second last element, followed by an ampersand (&) and then the last element to the answer variable. We break out of the loop at this point.

We output the answer variable which gives the desired result.

Here is a link to the code: Kata Day 10

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment