Writing code
Tags: javascript, npm, node, development
Published: 2020-08-18 09:36:09

---
title: Writing code
published: true
description: Building your first JavaScript package
tags: javascript, npm, nodejs, development
series: Building your first JavaScript package
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/8fi37fe23svbvtukdzww.jpg
---

Repository for this part is available on git branch `writing-code`

{% github andrevarandas/mood-sentences no-readme %}

## Writing code!

At last, we are going to write some code. Start by creating a `src` folder at the root of our project. This folder will be home for all our code. We may add subfolders to it, but all code goes into `src`!

`mkdir src`

After that, let's add our main JavaScript file, let's be bold and call it `index.js` 

`touch src/index.js`

We will also need another file - the JSON file that will contain our mood sentences.

`touch src/mood-sentences.json`

Add the file contents:

```json
{
    "anger": [
        "I'm furious",
        "That really drives me up the wall",
        "I go bananas",
        "I want to tear my hair out",
        "My blood is boiling"
    ],
    "excitement": [
        "I can't believe it",
        "Im really stoked",
        "That's fantastic",
        "How awesome",
        "I'm very excited"
    ],
    "boredom": [
        "It does nothing for me",
        "I can't say I find it interesting",
        "I can’t see what all the fuss is about",
        "It bores me to tears",
        "What a bore"
    ],
    "happiness": [
        "I'm very pleased",
        "I'm over the moon",
        "I'm on cloud nine",
        "I'm pleased as a punch",
        "I'm on top of the world"
    ]
}
```

> Please ignore the quality of the sentences. Let's use it as it is, for now, we can always improve them later.

Now we are ready to start adding some code to our `index.js`. 

We want to start by importing the JSON file. 

```javascript
const moods = require('./mood-sentences.json')
```

Then we want to create a method that will receive a string for the mood and return a random sentence for it.

```javascript
const moods = require('./mood-sentences.json')

const getRandom = (mood) => {
  if (mood in moods) {
    return getRandomItemFromArray(moods[mood])
  }

  throw new Error(`Requested mood "${mood}" is not in the moods list!`)
}
```

> 💡 We should care about error handling, and assume that things can go wrong. 

Notice that we call `getRandomItemFromArray`, let's define that function now:

```javascript
const moods = require('./mood-sentences.json')

const getRandomItemFromArray = (array) => array[Math.floor(Math.random() * array.length)]

const getRandom = (mood) => {
  if (mood in moods) {
    return getRandomItemFromArray(moods[mood])
  }

  throw new Error(`Requested mood "${mood}" is not in the moods list!`)
}
```

To make the life of the user easier, we will add a simple "enum" and call it just list, so even if the users don't know all the available moods, we provide them.

```javascript
const moods = require('./mood-sentences.json')

const getRandomItemFromArray = (array) => array[Math.floor(Math.random() * array.length)]

const getRandom = (mood) => {
  if (mood in moods) {
    return getRandomItemFromArray(moods[mood])
  }

  throw new Error(`Requested mood "${mood}" is not in the moods list!`)
}

const list = {
  ANGER: 'anger',
  BOREDOM: 'boredom',
  EXCITEMENT: 'excitement',
  HAPPINESS: 'happiness'
}
```

We can always add more moods, we just need to make sure that the object values exist in the JSON file.

That's all the code we need for our simple package. We just need to actually export them, so our users can use it properly.

```javascript
const moods = require('./mood-sentences.json')

const getRandomItemFromArray = (array) => array[Math.floor(Math.random() * array.length)]

const getRandom = (mood) => {
  if (mood in moods) {
    return getRandomItemFromArray(moods[mood])
  }

  throw new Error(`Requested mood "${mood}" is not in the moods list!`)
}

const list = {
  ANGER: 'anger',
  BOREDOM: 'boredom',
  EXCITEMENT: 'excitement',
  HAPPINESS: 'happiness'
}

module.exports = {
  all: moods,
  anger: moods.anger,
  boredom: moods.boredom,
  excitement: moods.excitement,
  happiness: moods.happiness,
  getRandom,
  list
}
```

Our simple package is ready! It's now probably a good idea to add some comments and [jsdoc](https://jsdoc.app/) strings to the file, so the users can get code hints when using our package.

Here's the full file, commented out:

```javascript
// Import our moods list
const moods = require('./mood-sentences.json')

/**
 * From the received array, returns a random element.
 *
 * @param {[]} array of items to choose from.
 *
 * @returns A random element from the array.
 */
const getRandomItemFromArray = (array) => array[Math.floor(Math.random() * array.length)]

/**
 * Enum of available moods.
 */
const list = {
  ANGER: 'anger',
  BOREDOM: 'boredom',
  EXCITEMENT: 'excitement',
  HAPPINESS: 'happiness'
}

/**
 * Gets a random sentence of the received mood.
 *
 * @param {list} mood to use.
 *
 * @throws Will throw if the received mood is not known, undefined or null
 *
 * @returns {string} a random sentence for the chosen mood.
 */
const getRandom = (mood) => {
  if (mood in moods) {
    return getRandomItemFromArray(moods[mood])
  }

  throw new Error(`Requested mood "${mood}" is not in the moods list!`)
}

module.exports = {
  all: moods,
  anger: moods.anger,
  boredom: moods.boredom,
  excitement: moods.excitement,
  happiness: moods.happiness,
  getRandom,
  list
}
```

You can see all the changes done for this chapter on Github writing-code chapter - [https://github.com/AndreVarandas/mood-sentences/tree/writing-code](https://github.com/AndreVarandas/mood-sentences/tree/writing-code)

Thanks for reading. That's all for this chapter, in the next one, we will start adding some tests!