Search code examples
discord.jsoperatorscommando

How to substract and divide numbers in loops discord.js


Coding a discord bot using the commando framework of discord.js v12.5, made an 'add' and 'multiply' command that adds every single number inputted by a user.

Here is the code for the 'add' command:

const Discord = require('discord.js')
const Commando = require('discord.js-commando')

module.exports = class AddCommand extends Commando.Command {
    constructor(client) {
        super(client, {
            name: 'add',
            group: 'math',
            memberName: 'add',
            description: 'Adds numbers',
            argsType: 'multiple',
        })
    }

    async run(message, args) {
        let sum = 0

        for (const arg of args) {
            sum += parseInt(arg)
        }

        const addCommandoEmbed = new Discord.MessageEmbed()
        .setTitle(`SUCCESS\n\n${args.join(' + ')} = ${sum}`)
        .setColor('#1be730')
        message.channel.send(addCommandoEmbed)
    }
}

I don't know how to use logical operators to make it substract every single number given, and how to divide every single number given, and give the remainder at the end.


Solution

  • You can use MathJS library.

    const mathjs = require("mathjs");
    
    const addCommandoEmbed = new Discord.MessageEmbed()
        .setTitle(`SUCCESS\n\n${args.join(' + ')} = ${mathjs.evaluate(args.join(" + "))}`)
        .setColor('#1be730');
    
    message.channel.send(addCommandoEmbed)