How to create an ASCII frequency table from a string in TypeScript

1 Answer

0 votes
function getASCIIFrequency(str: string) {
    const frequencyTable: any[] = new Array(128).fill(0);

    for (let i: number = 0; i < str.length; i++) {
        frequencyTable[str.charCodeAt(i)]++;
    }

    return frequencyTable.reduce((accumulator, count, index) => {
        if (count > 0) {
            accumulator[String.fromCharCode(index)] = count;
        }
        return accumulator;
    }, {});
}

const str: string = "typescript c c++ c# java python php";

const asciiFrequency: any = getASCIIFrequency(str);

console.log(asciiFrequency);



/*
run:
  
{
  " ": 6,
  "#": 1,
  "+": 2,
  "a": 2,
  "c": 4,
  "e": 1,
  "h": 2,
  "i": 1,
  "j": 1,
  "n": 1,
  "o": 1,
  "p": 5,
  "r": 1,
  "s": 1,
  "t": 3,
  "v": 1,
  "y": 2
}
           
*/

 



answered Oct 16, 2024 by avibootz

Related questions

1 answer 112 views
1 answer 115 views
1 answer 114 views
1 answer 119 views
1 answer 133 views
1 answer 115 views
1 answer 107 views
...