简体   繁体   中英

Is there a way to write this small piece of code in a more elegant, optimized way? (ES6)

I have been trying to teach myself ES6 for a short while now. Here is a small example of stuff that I learned, like let, const and => functions. Is there a more elegant or shorter way to write this? Maybe replace for loop with forEach? Any tips and help are welcome.

'use strict';
const countChar = (string, ch) => {
    let counted = 0;
    for (let i = 0; i < string.length; i++) {
        if (string.charAt(i) === ch) {
            counted += 1;
        }
    }
    return counted;
};

const countBs = string => countChar(string, 'B');

console.log(countBs('BBC'));
console.log(countChar('kakkerlak', 'k'));

Here's another way to shorten it

 'use strict'; const countChar = (string, ch) => string.split(ch).length - 1; const countBs = string => countChar(string, 'B'); console.log(countBs('BBC')); console.log(countChar('kakkerlak', 'k')); 

您是否考虑过正则表达式

 alert('kakkerlak'.match(/k/g).length) 

Not necessarily related to ES6, but a more functional approach, eg using filter() seems nice here:

 const countChar = (string, needle) => string.split('') .filter(char => char === needle) .length; const countBs = string => countChar(string, 'B'); console.log(countBs('BBC')); console.log(countChar('kakkerlak', 'k')); 

Elegance is in the eye of the beholder but here's a way to reduce it further by using reduce :

 'use strict'; const countChar = (string, ch) => string.split('').reduce((sum, c) => sum + (c === ch), 0); const countBs = string => countChar(string, 'B'); console.log(countBs('BBC')); console.log(countChar('kakkerlak', 'k')); 

It works by converting the string into an array of characters then summing up the number of characters in that array which match ch . I also (ab)use the fact that true converts to 1 and false converts to 0 so adding c === ch to the running sum will add 1 if it matches and 0 if it doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM