Created
February 17, 2020 12:51
-
-
Save Narshe1412/838c5f0e1582bca0a023dfcc44c05fe4 to your computer and use it in GitHub Desktop.
TypeScript round function with a default return value if the object provided is not defined or not a number
This file contains 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
/** | |
* Given an object with a property, it tests if the property is a number and returns the round of that | |
* Otherwise returns the value provided by defaultValue, or null | |
* @param obj The object that contains the property to test | |
* @param prop The property that will be tested | |
* @param decimalsToRound The number of decimals to round to | |
* @param defaultValue The default value provided if it cannot complete the transaction | |
*/ | |
export const roundOrDefault = (obj: any, prop: string, decimalsToRound: number, defaultValue = null) => { | |
if (!obj) { | |
return defaultValue; | |
} | |
if (obj && !obj.hasOwnProperty(prop)) { | |
return defaultValue; | |
} | |
if (obj && obj.hasOwnProperty(prop)) { | |
if (typeof obj[prop] !== 'number') { | |
return defaultValue; | |
} else { | |
return Math.round(obj[prop] * 10 ** decimalsToRound) / 10 ** decimalsToRound; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment