Reputation: 55
This is my code:
nicknames = {'RAM' : 'Black', 'ELC': 'Mamba', 'FAD' : 'Samba', 'NOP' : 'STOP'}
const nickGet = (initials) => {
return initials.match(/.{1,3}/g).reduce((arr, trio) => {
if (!nicknames[trio]) throw new Error('Invalid trio')
return [...arr, nicknames[trio]]
})
}
I am getting the below output when I run nickGet("ELCRAM"):
["E", "L", "C", "Black"]
I know that if I want to make this work, I should set an initial value of [] to reduce. However, I'm wondering why when I don't, I get this specific out. How is ELC being divided into separate values in my array? What is the logic behind it here?
Thank you!
EDIT, trying to do it with map function:
var nicknames = { RAM: 'Black', ELC: 'Mamba', FAD: 'Samba', NOP: 'STOP' };
const nickGet = (initials) => {
var nick = initials.match(/.../g).map((trio) => {
if (!nicknames[trio]) throw new Error('Invalid trio')
return nicknames[trio]
}, []);
nick.length = nick.findIndex(element => element == "STOP");
return nick;
};
Anyway to do it so that maps just stops when it hits STOP? Not sure what to replace "nothing" with if any.
Upvotes: 1
Views: 57
Reputation: 386680
You do not supply an empty array as start value for the accumulator.
In the fist loop, the string ELC
is spreaded into single characters, because this is the value for arr
. As trio
, you get RAM
and this value is converted to 'Black'
.
var nicknames = { RAM: 'Black', ELC: 'Mamba', FAD: 'Samba', NOP: 'STOP' };
const nickGet = (initials) => {
return initials.match(/.../g).reduce((arr, trio) => {
if (!nicknames[trio]) throw new Error('Invalid trio')
return [...arr, nicknames[trio]];
}, []);
};
console.log(nickGet('ELCRAM'));
console.log([...'ELC']);
Upvotes: 3