Add countChars function
This commit is contained in:
37
commands/countChars.ts
Normal file
37
commands/countChars.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const { SlashCommandBuilder, Discord } = require('discord.js');
|
||||
|
||||
module.exports = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('count_chars')
|
||||
.setDescription('Counts the number of characters in a string')
|
||||
.addStringOption( option =>
|
||||
option.setName('string')
|
||||
.setDescription("String to count characters in")
|
||||
.setRequired(true)
|
||||
),
|
||||
async execute(interaction) {
|
||||
var inputString = interaction.options.getString('string');
|
||||
await interaction.reply(countChars(inputString));
|
||||
console.log("User " + interaction.user.tag + " ran /count_chars");
|
||||
},
|
||||
};
|
||||
|
||||
function countChars(string) {
|
||||
var outputString = "";
|
||||
string = string.toLowerCase();
|
||||
var letterCount = Array(26).fill(0); // Creates an array with 26 values, all equaling 0.
|
||||
for (let i = 0; i < string.length; ++i) {
|
||||
let currentChar = string.charAt(i);
|
||||
let arrayIndex = currentChar.charCodeAt(0) - 97;
|
||||
if (string.charAt(i).search(/^[a-z]+$/) === 0) {
|
||||
letterCount[arrayIndex]++;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < letterCount.length; ++i) {
|
||||
if (letterCount[i] > 0) {
|
||||
outputString += "Number of " + String.fromCharCode(i + 97).toUpperCase() + "'s: " + letterCount[i] + "\n";
|
||||
}
|
||||
}
|
||||
return outputString;
|
||||
}
|
||||
//console.log(countChars("test string"));
|
Reference in New Issue
Block a user