- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculating resistance of n devices - JavaScript
In Physics, the equivalent resistance of say 3 resistors connected in series is given by −
R = R1 + R2 + R3
And the equivalent resistance of resistors connected in parallel is given by −
R = (1/R1) + (1/R2) + (1/R3)
We are required to write a JavaScript function that takes a string having two possible values, 'series' or 'parallel' and then n numbers representing the resistance of n resistors.
And the function should return the equivalent resistance of these resistors.
Example
Let us write the code for this function.
const r1 = 5, r2 = 7, r3 = 9; const equivalentResistance = (combination = 'parallel', ...resistors) => { if(combination === 'parallel'){ return resistors.reduce((acc, val) => (1/acc) + (1/val)); }; return resistors.reduce((acc, val) => acc + val); }; console.log(equivalentResistance('parallel', r1, r2, r3));
Output
Following is the output in the console −
3.0277777777777777
Advertisements