1

Implementing Reduce in javascript using TDD

 1 year ago
source link: https://blog.navneet.dev/reduce-in-javascript-using-tdd/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In JavaScript, the Array.prototype.reduce() method is a powerful tool for reducing an array into a single value by executing a provided function on each element. In this blog post, we'll explore how to create a custom myReduce function using Test-Driven Development (TDD) techniques and leverage prototype inheritance to extend the functionality of arrays.

Created using http://reduce.surge.sh/

Setting Up the Development Environment

To begin, create a new folder for your project and initialize it with a package.json file by running npm init in your terminal. Install the testing framework mocha and the assertion library chai as dev dependencies by running npm install --save-dev mocha chai. We'll use these tools to drive our development process.

Mocha is the test runner, or test “framework”. It’s the top-level tool in this hierarchy. Mocha is responsible for finding and loading test files, transpile them, and running the test code itself: the describe and it blocks that compose the tests.

Chai is the assertion library. It supplies the expect and assert calls we’ll use in the tests to verify everything is working correctly.

mkdir myreduce
cd myreduce
npm init
npm install --save-dev mocha chai

Creating the Test Suite

In the project's root directory, create a new file called myReduce.test.js. This file will contain our test suite for the myReduce function.

So Let's take an example where our accumulator function is adding values.

  • When we pass an array of integers without the initial values it should return the sum of the numbers.
  • When we pass an array of integers with the initial values it should return the sum of the numbers with the initial value.
  • When the initial value is not passed, it takes the first element as the initial value.
// myReduce.test.js

const { expect } = require('chai');
const { myReduce } = require('./myReduce');

describe('myReduce', () => {
  it('should reduce an array to a single value', () => {
    Array.prototype.myReduce = myReduce;
    const arr = [1, 2, 3, 4, 5];
    const sum = (accumulator, currentValue) => accumulator + currentValue;
    expect(arr.myReduce(sum)).to.equal(15);
  });
	
  it('should reduce an array to a single value using the initial value', () => {
    Array.prototype.myReduce = myReduce;
    const arr = [1, 2, 3, 4, 5];
    const sum = (accumulator, currentValue) => accumulator + currentValue;
    expect(arr.myReduce(sum, 10)).to.equal(25);
  });
  
});
Can you think of any more edge cases?   How about a different accumulator function?  Writing the first test could have a slightly higher threshold for a developer but once you add one case it's easy to add other test cases. Hence saving up tons of time to do manual tests on various scenarios.

Implementing the myReduce Function

Create a new file called myReduce.js in the project's root directory. This file will contain the implementation of the myReduce function.

// myReduce.js

const myReduce = function (callback, initialValue) {
    if (this.length === 0 && initialValue === undefined) {
      throw new TypeError('Reduce of empty array with no initial value');
    }
  
    let accumulator = initialValue !== undefined ? initialValue : this[0];
    const startIndex = initialValue !== undefined ? 0 : 1;
  
    for (let i = startIndex; i < this.length; i++) {
      accumulator = callback(accumulator, this[i], i, this);
    }
  
    return accumulator;
};

Array.prototype.myReduce = myReduce;
  
module.exports = { myReduce };
  

Running the Tests

Open your terminal and run npx mocha to execute the tests.

Screenshot-2023-05-29-at-6.20.12-PM.png

Passing tests.

In this blog post, we've walked through the process of creating a myReduce function using Test-Driven Development (TDD) techniques and prototype inheritance in JavaScript. By writing tests first and incrementally improving our implementation, we can ensure that our custom function behaves correctly and consistently.

Remember, TDD encourages writing tests that cover different scenarios and edge cases, making your code more robust and maintainable. Additionally, prototype inheritance allows you to extend JavaScript's built-in objects, providing you with the flexibility to customize and enhance their functionality.

Hope you liked the content. Reach out to me if you have doubts or just to say Hi. Feedbacks are always welcome and appreciated. Subscribe to this blog if you want to receive an update whenever I publish a new blog.
Twitter  Portfolio

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK