gkz / prelude-ls

prelude.ls is a functionally oriented utility library - powerful and flexible, almost all of functions are curried. It is written in, and is the recommended base library for, http://livescript.net
http://preludels.com/
MIT License
424 stars 57 forks source link

`filter` should be extended with obj condition #112

Closed askucher closed 6 years ago

askucher commented 6 years ago

filter works fine with functions but sometimes better to filter by object

o = [{ x: 1, y: 2}, { x: 2 }]
o |> filter { x: 1 }  

expected => [{ x: 1, y: 2}] actual thrown n is not a function

gkz commented 6 years ago

I think this is easy enough:

o = [{ x: 1, y: 2}, { x: 2 }, { x: 2, y: 3}]
o |> filter (.x == 1)
o |> filter (.x == 2 && it.y == 3)
anko commented 6 years ago

How to do it yourself if you want that API anyway:

compare = (template, actual) -->
  (for let key, value of template
    actual[key] is value)
    .every (is true)

o = [{ x: 1, y: 2}, { x: 2 }, { x: 2, y: 3}]

o.filter compare { x: 1 }
|> console.log # => [ { x: 1, y: 2 } ]
askucher commented 6 years ago

@gkz sometimes better build a condition as object. for instance for filtering the table