filter - FilterWithKeys for Javascript? -
in ramda, we're given lot of higher-order combinators practical work. 1 that's convenient .filter()
utility - given array.filter()
function in es6, ramda (and lodash believe) give ability filter on objects well. me, tool filter on both keys , values @ same time.
the const
keyword in es6 powerful tool - using arbitrary (non-object) values, can have guarantee value never change rest of block (and deduce bugs, lots of other nice gains). other practical way filter keys , values object using for .. in
, forces use mutable variable:
let xs = {...} (const k in xs) { if (someproperty(k,xs[k])) { delete xs[k] } }
i argue using filterwithkey
alleviate issue:
const xs = filterwithkey(someproperty, {...})
is there in popular javascript library? haven't seen in ramda or lodash yet, i'm not sure else look. think suitable implementation though:
function filterwithkey (p,xs) { r.topairs(xs).reduce((acc,x) => { const k = x[0] const v = x[1] return p(k,v) ? acc[k] = v : acc }) }
it still requires act of rebuilding object though. there better solution?
ramda added ability filter objects on values; until natively supported lists, , otherwise delegate object's filter
method if existed. in issue 1429 extended plain objects well.
there great deal of discussion in issue possibility of supporting keys
parameter well, demonstrated @ odds other parts of library.
i added section ramda's cookbook describing 1 way write function yourself:
const filterwithkeys = (pred, obj) => r.pipe( r.topairs, r.filter(r.apply(pred)), r.frompairs )(obj); filterwithkeys( (key, val) => key.length === val, {red: 3, blue: 5, green: 5, yellow: 2} ); //=> {red: 3, green: 5}
if have more useful short example, i'd love include instead.
like in ramda world, not mutate input data. important in functional programming, , not interested in working version built way. in other words, see feature:
it still requires act of rebuilding object though.
Comments
Post a Comment