I am trying to get my head around both composed functions and pure functions.
I have an object with a mixture of data. On some values I need to:
- remove the value's units
- parse string to integer
- Convert to value decimal
I have written three functions attempting to make them pure in the sense that they only do one thing but strictly speaking, they are mutating state. I'm not sure how to avoid mutating state though and if this technically makes it not a pure function?
My three "pure" functions are:
function parseValue(val) {
return typeof val === 'number' ? val : parseInt(val)
}
function stripUnits(val) {
return typeof val === 'string' ? val.match(/\d+/)[0] : val
}
function convertToDecimal(val) {
return val / 100
}
I am then trying to compose these functions into one function with the help of lodash compose()
function prepValue(val) {
return compose(stripUnits, parseValue, convertToDecimal)
}
When I try run this console.log("prepValue", prepValue(weather.current.temperature))
I get the following in the terminal:
prepValue function (){var n=arguments,e=n[0];if(o&&1==n.length&&of(e))return o.plant(e).value();for(var u=0,n=r?t[u].apply(this,n):e;++u<r;)n=t[u].call(this,n);return n}
So the main things is,
- How can I make my three functions "pure"
- How can I compose these functions into 1