DEV Community

Ibrahim Khan
Ibrahim Khan

Posted on

How I practice Problem Solving in JavaScript with Jest

Algorithms and data structure are the founding pillars for any software engineer. But it the knowledge depends on the practice of it. Most of the time in my work, I don't need to use all of those algorithms. That's why I try to solve problems from Leet Code so that I can stay in the loop and don't forget all the basics (duhh 🤨).

But Why?

One problem that I consistenty face is that, when I change the code to improve my implementation, it takes too much time on LeetCode to run my code and return the results. At first I used to keep and array of inputs and outputs, and compare them manually. Although it was tedious, it did what I wanted to do, run all the cases locally for faster results. When I started following TDD (Test-Driven Development) process at my workplace, it came to my mind that I can write small test-cases for my implementation.

How I do it now?

Initially I created an Node.js project with NPM

npm init

Then installed Jest

npm install --save jest

The project structure looks like this -

./LeetCode
    |--- main.js
    |--- main.test.js
    |--- package.json

My package.json looks like this -

{
  "name": "LeetCode",

  "version": "1.0.0",
  "description": "",
  "scripts": {
    "start": "node main.js",
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^24.9.0"
  }
}

I write my implementation on main.js -

const romanMap = {
  '1': 'I', '2': 'II', '3': 'III', '4': 'IV', '5': 'V', '6': 'VI', '7': 'VII', '8': 'VIII', '9': 'IX',
  '10': 'X'
}

/**
 * @param {number} num
 * @return {string}
 */
var intToRoman = function(num) {
    return romanMap[num.toString()];
};

module.exports = intToRoman;

Then write my test-cases on main.test.js -

const func = require('./main');

test('Outputs III', () => {
  expect(func(3)).toBe('III');
});

test('Outputs IV', () => {
  expect(func(5)).toBe('IV');
});

test('Outputs IX', () => {
  expect(func(9)).toBe('IX');
});

Now I can run all test-cases at once -

npm test

RUNPASSED

Now, let's say that my implementation was wrong. What will happen then?

Jest will print out the diff of the expected output and the output from running the test.

RUNFAILED


On LeetCode, they don't provide all the test-cases. So, I start with the sample output, then gradually add new cases when I get error after submitting my code. That way, I can write a basic solution and gradually build my testing code. When that is accepted, then I can easily write more optimized code and test them locally. But of course I submit that code on LeetCode afterwards for checking.

Should you do it too?

No really, that depends on how you try to approach it. Everyone has their own flow of keeping their basic on the check. But, do tell me how you do it.

Top comments (0)