Reputation: 9251
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:
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,
Upvotes: 1
Views: 104
Reputation: 12161
You need to "create the function composition" before calling it.
function parseValue(val) { console.log(val)
return typeof val === 'number' ? val : parseInt(val)
}
function stripUnits(val) { console.log(val)
return typeof val === 'string' ? val.match(/\d+/)[0] : val
}
function convertToDecimal(val) {console.log(val)
return val / 100
}
function prepValue(val) {
return _.compose(stripUnits, parseValue, convertToDecimal)(val);
}
console.log("prepValue", prepValue('001232'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.fp.js"></script>
Upvotes: 1
Reputation: 136094
The only mistake you made is not calling the resulting composed method with val
as the argument:
function prepValue(val) {
return compose(stripUnits, parseValue, convertToDecimal)(val);
}
Upvotes: 2