2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today. the problem set focuses on JavaScript and Python. Let’s dive in!
Format a string of names like ‘Bart, Lisa & Maggie’
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:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'
namelist([ {'name': 'Bart'} ])
# returns 'Bart'
namelist([])
# returns ''
Note: all the hashes are pre-validated and will only contain A-Z, a-z, ‘-‘ and ‘.’.
JavaScript solution:
function list(names){
let str = '';
if (names.length !== 0) {
let last = names.pop();
str = names.map( (val, i, arr) => {
if (i !== arr[arr.length - 1]) {
return val.name;
}
}).join(', ')
str += str !== '' ? ' & ' + last.name : last.name;
}
return str;
}
Python Solution:
def namelist(names):
str = ''
if len(names) != 0:
arr = []
for i in range(0, len(names) - 1):
arr.append(names[i]['name'])
str = ', '.join(arr)
str += ' & ' + names[-1]['name'] if str != '' else names[-1]['name']
return str
Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*
All credit to problem sets goes to codewars
What if the list had 1 name?
LikeLike
“All of my solutions are commented to explain my thinking.”
I can’t see your commentary on this solution and I wish I could!
Regardless thanks for sharing.
LikeLike
How do you get in the job, I am a aspiring self taught developer I hope to one day be a great developer
LikeLike