HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Calculate the quotient and remainder of a division in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptandremaindercalculatethequotientdivision

Problem

Python's divmod() comes in handy quite often. Its purpose is to return a 2-tuple consisting of the quotient and remainder of a division. For example, divmod(8, 3) returns (2, 2) because 8 / 3 = 2 with a remainder of 2.
In order to implement divmod() in JavaScript, we can use the built-in Math.floor() function to get the quotient and the modulo operator (%) to get the remainder of the division x / y.

Solution

const divmod = (x, y) => [Math.floor(x / y), x % y];

divmod(8, 3); // [2, 2]
divmod(3, 8); // [0, 3]
divmod(5, 5); // [1, 0]

Code Snippets

const divmod = (x, y) => [Math.floor(x / y), x % y];

divmod(8, 3); // [2, 2]
divmod(3, 8); // [0, 3]
divmod(5, 5); // [1, 0]

Context

From 30-seconds-of-code: divmod

Revisions (0)

No revisions yet.