2
\$\begingroup\$

I have a Slack bot that takes a stream of messages and the idea is that if 3 different users repeat the same message, the bot will also mime that message.

I am just beginning with RXJS and I am trying to figure out the correct, most idiomatic way to refactor the following code. Is it even possible with what I'm trying to do here?

JSBin

let repeat = {
    count: 0,
    message: '',
    users: []
};

const reset = () => {
    repeat.count = 0;
    repeat.message = '';
    repeat.users.length = 0;
};

module.exports = (source) => {
    source
        .filter(message => {
            // Sets initial message if there is no prior message
            if (!repeat.message) {
                repeat.message = message.text;
                repeat.users.push(message.user);

                return true;
            }

            // The message is the same and it's not repeated by a known user
            if (repeat.message === message.text && !!~repeat.users.indexOf(message.user)) {
                repeat.users.push(message.user);

                return true;
            }

            // Starts a new sequence
            reset();
            repeat.users.push(message.user);
            repeat.message = message.text;

            return false;
        })
        .subscribe(message => {
            repeat.count++;

            if (repeat.count === 3) {
                console.log(message.text);
                reset();
            }
        });
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.