重构我的JavaScript代码,以删除更多而不仅仅是空白



下面的代码是功能性的,但我想重构!==部分,允许我的三进制只运行在非空白的值上,这样我就可以包括边缘情况测试。这将包括任何非字母值以及空白,我知道regex可能起作用,但我找不到一个漂亮的方法将其合并到三元操作之前的if()语句中。

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'));

主要有两个选项,正则表达式和字符码,如果有更多的方法,欢迎编辑

const codes = ['A', 'Z', 'a', 'z'].map(x => x.charCodeAt(0))
console.log(codes)
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] !== ' ') {                       // old
//if (/[A-Za-z]/.test(strPos[i])) {                 // regex
let code = strPos.charCodeAt(i)
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) { // charcode
result[strPos[i]] ? result[strPos[i]].push(i) : (result[strPos[i]] = [i]);
}
}
return result;
};
console.log(letterPositions('aa bb cc'));

你也可以这样做…

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;}

相关内容

最新更新