Reputation: 666
js and I am trying to learn it by trying to use that in my code in bits and pieces.
The problem I am trying to solve is to check if an object is null or not. If it is null then return a blank object else return the original object.
code written so far:
R.ifElse(isEmptyObj, R.always({}), R.always)({a:1})
Now the problem is if isEmpty return true, then R.always return a function that returns {}. But then isEmpty is false we want to return the same object passed to the function, so R.always get executed with that object so we get a function as output.
So, in one condition I get an object and in other I get a function.
Upvotes: 0
Views: 911
Reputation: 193348
When R.always
is called the 1st time with a value (let's call it X), it returns a 2nd function that will always return the value the 1st function was called with (X). Since you call the R.always
without calling it first with a parameter, the result you get is the 2nd function.
In this case you want to pass the original value supplied to R.ifElse
, so use R.identity
:
const { ifElse, isNil, always, identity } = R
const fn = ifElse(isNil, always({}), identity)
console.log(fn({a:1})) // {a:1}
console.log(fn(null)) // {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
However, since you only want to return an empty object, if the original is null
(or undefined
if you use R.isNil
), you can replace the R.ifElse
with R.when
. Using R.when
the original value (the object) would be returned if the condition fails:
const { when, isNil, always } = R
const fn = when(isNil, always({}))
console.log(fn({a:1})) // {a:1}
console.log(fn(null)) // {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
Upvotes: 4