Categories: JavaScript

Helper function(s)

Writing the Slackbot, which communicates via text messages so there are plenty of places where there are numerals being referred to in text form, which means there are often cases where a word is either singular or plural, depending on whether it’s referring to one of something or more than one of something.

So, I wrote a quick helper function called add_s().

// utility function to add an s to a word if the number it refers to is plural
// takes the integer number
// returns a string that is either "" (empty) or "s"

function add_s(num) {
 var ret_str = "s";
 if (num == 1) {
 ret_str = "";

An example usage would be like this:

return_string = return_string + result.toString() + " month" + add_s(result);

So, the output in Slack looks like this:


or possibly:


That’s pretty cool.

Currently, the bot just assumes a month is 30 days. That’s why it says “about”. The algorithm for computing the actual number of months from one month to another is a little bit complicated, but I’m working on a solution that is more precise.

Iterate till it pops.

Article info