The following code is functional but I would like to refactor the !== part that allows my ternary to run only on values that are not white space so I can include edge case test’s. This would include any non letter value as well as white space and I know that regex may play a part but I can’t find a niftty way to incorporate it into the if() statement that precedes the ternary operations.
JavaScript
x
16
16
1
const letterPositions = function(strPos) {
2
if (typeof strPos !== 'string') {
3
return console.log('Sorry your input is not a string');
4
}
5
6
const result = {};
7
for (let i = 0; i < strPos.length; i++) {
8
if (strPos[i] !== ' ') {
9
result[strPos[i]] ? result[strPos[i]].push(i) : (result[strPos[i]] = [i]);
10
}
11
}
12
13
return result;
14
};
15
16
console.log(letterPositions('aa bb cc'));
Advertisement
Answer
you can also do that…
JavaScript
1
9
1
const letterPositions = str =>
2
{
3
if (typeof str !== 'string')
4
return console.log('Sorry your input is not a string' )
5
6
return [str].reduce((r,l,i)=>((l===' ')?null:(r[l]??=[],r[l].push(i)),r),{})
7
}
8
9
console.log( letterPositions('aa bb cc') )
JavaScript
1
2
1
.as-console-wrapper {max-height: 100% !important;top: 0;}
2
.as-console-row::after {display: none !important;}