Subtracting numbers will always result in a positive number

I need some assistance with a method I am developing for an array function called RPNCalculator. Unfortunately, it is not functioning correctly at the moment.

An issue arises when performing subtraction operations within the calculator. For example, when subtracting 3 from 8, the result is returning 5 instead of -5. Similarly, when subtracting 3 from 4, it returns 1 instead of -1. This discrepancy can be observed in the num variable.

Your help in resolving this problem would be greatly appreciated.

RPN values: [2, 3 ,4]

RPNCalculator.prototype.minus = function() {
console.log("First item " + this[this.length - 2] + "\nLast Item " + this[this.length - 1]); 
        /* Logs:First item 3
                Last Item 4 */
var num = this.pop(this[this.length - 2]) - this.pop(this[this.length - 1]);
console.log(num);    // logs 1
this.push(num);
};

Answer №1

The issue lies in the way you are utilizing the pop method. When you use pop, it removes the last element from the array and returns that removed item. To correct this, update your function as follows:

RPNCalculator.prototype.minus = function() {
  let lastNum = this.pop();
  let firstNum = this.pop();
  this.push(firstNum - lastNum);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I implement $compile to execute a function on every row using angularjs and razor?

UPDATE: It seems that there is some confusion here, I am looking to apply the function to all rows, without using '', "", '"... After conducting some research, I have discovered that I will need to utilize $compile, but I am ...

The issue of losing the setTimeout value when changing tabs

I am trying to animate logos in several columns with a delay between each column using JavaScript. However, I'm facing an issue where setTimeout resets when switching tabs on the browser, causing all columns to animate at the same time. Here is my cur ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...

Encountering an issue in Angular 8 where there is a difficulty in reading the property 'NODE_NDEBUG' when attempting to serve the application

An issue has been identified in the assert-plus library at ../node_modules/assert-plus/assert.js where it is encountering difficulties reading 'NODE_NDEBUG' from 'process.env', as highlighted in the code snippet below module.exports = ...

Can data be fetched from a local port using either Javascript or ASP.NET?

I have created the code below to broadcast data in a Windows application using C#. UdpClient server = new UdpClient("127.0.0.1", 9050); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); ...

Is there a more efficient method to tally specific elements in a sparse array?

Review the TypeScript code snippet below: const myArray: Array<string> = new Array(); myArray[5] = 'hello'; myArray[7] = 'world'; const len = myArray.length; let totalLen = 0; myArray.forEach( arr => totalLen++); console.log(& ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

Is there a universal method for sorting arrays of arrays that sorts by each element starting from the first and continuing to the nth element?

Suppose I need to sort arrays of an array in ascending order, where the first element is min, then the second element is min, and so on. Here's how you can achieve this using the sort method: Array with 2 elements const arrayOfArray=[[2,1],[0,2],[ ...

Navigating to the specific item that a directive is linked to

I am looking to develop a directive that can be applied to elements to adjust their maximum height to be equal to the height of the window minus the distance from the top of the element to the top of the window. I have attempted it in the following manner ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...

Enhance your JQuery UI autocomplete feature by including images and multiple fields for a more interactive user experience

I am looking to incorporate Autocomplete functionality that will showcase names and avatars similar to the Facebook autocomplete feature. In a recent post Jquery UI autocomplete - images IN the results overlay, not outside like the demo and in the provide ...

Implementing real-time style changes with Angular 6 through Environment Variables

Attempting to dynamically change styles in Angular 6 using environment variables has been a success for me. Here is how my file structure is organized: src -app -assets -environments -scss -theme1.scss -theme2.scss -_variables.scss -styles.sc ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

What is the process of utilizing multiple npm registries within Yarn?

Currently, I am facing a challenge while setting up Yarn 0.17.9 in our environment due to issues with our registry setup. Our environment involves two registries - the official npmjs registry and our own internal network registry (Sinopia). The main issue ...

Incorporate live data from a Winston log file directly into a React application

I have a Node backend where I am generating a winston JSON log file which is essentially an array of JSON objects. On my React frontend, I want to display the contents of this log file in real-time. Is there a way to achieve this without passing it throu ...

Unit test failing due to Vue v-model binding not functioning as expected

I am attempting to monitor the value of the #username element when I change the data in form.username // Regitser.vue ... <div class="form-group"> <label for="username">Username</label> <input type="text ...

Employ the Google Charting library for creating a GeoChart that is currently not displaying

Hello everyone. I'm having a bit of an issue with my web page development. I've been trying to add a GeoChart, but no matter how many times I copy-paste the code from the Google developer's website, the map just won't show up. I must be ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Unable to establish session using jquery

I am trying to set a session using jQuery, but I keep encountering this error. I have looked for solutions online, but haven't been able to find one that works. Can someone please help me out? Thank you! ...

Encountering the error message "{error: 'Operation `users.findOne()` buffering timed out after 10000ms'}" while trying to access my app on localhost

In my project, I have organized my code into 'client' and 'server' folders. The server side of the application is built using Express and successfully connected to a MongoDB database in the server folder using nodemon. https://i.sstati ...