Skip to content

Instantly share code, notes, and snippets.

@jwulf
Created March 6, 2018 22:29
Show Gist options
  • Save jwulf/ed9c22e216d3e954b158f2d279c4f15d to your computer and use it in GitHub Desktop.
Save jwulf/ed9c22e216d3e954b158f2d279c4f15d to your computer and use it in GitHub Desktop.
Lodash's createMathOperation in ES6
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