Last active
August 14, 2019 16:31
-
-
Save nanodracula/4511ff32f85e737c4b2e4943ebe09610 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict' | |
| /** | |
| * Calculate relative value from number and percentage. | |
| * | |
| * @example f(500, 10) -> 50 | |
| * @example f(500, 200) -> 1000 | |
| */ | |
| function numberFromPercentage(value, percentage) { | |
| return (value / 100) * percentage | |
| } | |
| /** | |
| * Calculate value, by given old value and % of grow\fall. | |
| * | |
| * @param {number} value - Old value from that we will be calculating new value. | |
| * @param {number} percentage - Number of % for growing (like '20'), or declining (use negative sigh like '-20'). | |
| * | |
| * @return {number} - New value, that was calculated. | |
| * | |
| * @example f(500, -300) -> 125 | |
| * @example f(500, 300) -> 2000 | |
| */ | |
| function percentToNumberChange(value, percentage) { | |
| const oldValue = Number(value) | |
| const nPercentage = Number(percentage) * -1 | |
| let result | |
| if (percentage < 0) { | |
| result = (oldValue / (100 + nPercentage)) * 100 | |
| } | |
| if (percentage > 0) { | |
| result = oldValue + (oldValue * Math.abs(nPercentage)) / 100 | |
| } | |
| return result | |
| } | |
| /** | |
| * Calculate difference in % between old and new values. | |
| * | |
| * @param {number} oldValue | |
| * @param {number} newValue | |
| * | |
| * @returns {number} - percentage, in what value grow or fall. | |
| * | |
| * @example f(300, 450) -> 50 | |
| * @example f(400, 300) -> -25 | |
| */ | |
| function percentChangeDifference(oldValue, newValue) { | |
| const value = (1 - Number(newValue) / Number(oldValue)) * 100 | |
| // How to change sign in number: https://stackoverflow.com/a/4652158 | |
| const percentage = value * -1 | |
| return percentage | |
| } | |
| module.exports = { | |
| numberFromPercentage, | |
| percentToNumberChange, | |
| percentChangeDifference, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment