Created
March 6, 2018 22:29
-
-
Save jwulf/ed9c22e216d3e954b158f2d279c4f15d to your computer and use it in GitHub Desktop.
Lodash's createMathOperation in ES6
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
import baseToNumber from './baseToNumber.js' | |
import baseToString from './baseToString.js' | |
/** | |
* Creates a function that performs a mathematical operation on two values. | |
* | |
* @private | |
* @param {Function} operator The function to perform the operation. | |
* @param {number} [defaultValue] The value used for `undefined` arguments. | |
* @returns {Function} Returns the new mathematical operation function. | |
*/ | |
function createMathOperation(operator, defaultValue) { | |
return (value, other) => { | |
if (value === undefined && other === undefined) { | |
return defaultValue | |
} | |
if (value !== undefined && other === undefined) { | |
return value | |
} | |
if (other !== undefined && value === undefined) { | |
return other | |
} | |
if (typeof value == 'string' || typeof other == 'string') { | |
value = baseToString(value) | |
other = baseToString(other) | |
} | |
else { | |
value = baseToNumber(value) | |
other = baseToNumber(other) | |
} | |
return operator(value, other) | |
} | |
} | |
export default createMathOperation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment