evilsoft/crocks

isMap Predicate

bennypowers opened this issue · 4 comments

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?

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);
}

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 } }

https://repl.it/@bennypowers/isMap

@bennypowers I ❤️ this. Glad you ran into a need for it!
totes 👍 this addition.