isMap Predicate
bennypowers opened this issue · 4 comments
bennypowers commented
Describe the solution you'd like
We've got isArray
and isPromise
, why not isMap
?
Describe alternatives for how you do this now
implement on my own
Code
function isMap(x)
return x instanceof Map;
}
amite commented
What's a good example of when this would be useful?
bennypowers commented
useful in input validation, for example
const isValidCache = or(isObject, isMap);
const entriesToMap = xs => new Map(xs);
const registerObject = compose(registerMap, entriesToMap, Object.entries);
const register = ifElse(isMap, registerMap, registerObject);
export function registerIconCache(cacheToRegister) {
if (!isValidCache(cacheToRegister)) throw new TypeError('registerIconCache: Map or Object expected');
return register(cacheToRegister);
}
bennypowers commented
could also be good for serializing data
const serialize = mapProps({ couldBeMap: when(isMap, compose(Object.fromEntries, entries)) })
const input = { couldBeMap: new Map([[1, 1], [2, 2]]) }
JSON.stringify(input, null, 2) // { couldBeMap: {} }
JSON.stringify(serialize(input) // { couldBeMap: { 1: 1, 2: 2 } }
evilsoft commented
@bennypowers I ❤️ this. Glad you ran into a need for it!
totes 👍 this addition.