Skip to content
Advertisement

How to subtract these two arrays

I am trying to subtract two matrices, I have a function that takes in those matrices and returns a new matrix that has been subtracted. I get this error in node.js: TypeError: (intermediate value).map is not a function

JavaScript

This is the function I use from my main file (note: I already have an instance of the class).

JavaScript

This is the class that I have created:

JavaScript

Advertisement

Answer

I’m going to recommend a complete code rewrite that focuses on a plain functions instead of classes and methods. We begin writing our matrix module below and will add an OOP-style interface in the second section of this post. –

JavaScript

Next we write our main module that uses the matrix module –

JavaScript
JavaScript

If you are more comfortable with an OOP-style interface, you we can add that to our matrix module easily. Notice how our Matrix class it is a simple wrapper around our existing plain functions –

JavaScript

And here’s our main module using our new Matrix interface –

JavaScript
JavaScript

Chain for days, if you wish –

JavaScript
JavaScript

As you can see we only write our matrix module once and it is flexible enough to use in functional-style and OOP-style. To see this module technique used in another setting, see this answer where we build a linked list.


Wondering why we went through so much trouble in matrix.toString? It’s so that the matrix can be nicely formatted even when element sizes differ –

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement