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.
const letterPositions = function(strPos) { if (typeof strPos !== 'string') { return console.log('Sorry your input is not a string'); } const result = {}; for (let i = 0; i < strPos.length; i++) { if (strPos[i] !== ' ') { result[strPos[i]] ? result[strPos[i]].push(i) : (result[strPos[i]] = [i]); } } return result; }; console.log(letterPositions('aa bb cc'));
Advertisement
Answer
you can also do that…
const letterPositions = str => { if (typeof str !== 'string') return console.log('Sorry your input is not a string' ) return [...str].reduce((r,l,i)=>((l===' ')?null:(r[l]??=[],r[l].push(i)),r),{}) } console.log( letterPositions('aa bb cc') )
.as-console-wrapper {max-height: 100% !important;top: 0;} .as-console-row::after {display: none !important;}