Clojurescript中的'find'函数匹配所有键/值

时间:2014-05-04 18:58:54

标签: clojurescript

我有兴趣使用Clojurescript中的核心函数创建如下所示的函数。

var props = [
    ["eyes", "brown"],
    ["age", "20"]
];

var people = [
    {eyes: "brown", age: "20", name: "Dick"},
    {eyes: "green", age: "30", name: "Tom"},
    {eyes: "blue", age: "20", name: "Sally"},
    {eyes: "brown", age: "20", name: "Harry"}
];

find = function (items, keyvals) {
    var results = items.slice(0);

    keyvals.forEach(function (keyval) {
        results = results.reduce(function (memo, item) {
            if (item.hasOwnProperty(keyval[0]) &&
                item[keyval[0]] === keyval[1]) {
                memo.push(item);
            }
            return memo;
        }, []);
    });

    return results;
};

document.body.innerHTML = JSON.stringify(find(people, props));

到目前为止,我有:

(defn find-all
  ([items k v]
    (filter #(= (k %) v) items))
  ([items k v & keyvals]
    (into [k v] keyvals)))

上述函数的第二部分会为每个(find-all items k v)调用keyvals,存储生成的匹配项,然后将这些匹配项提供给下一个调用项。 items将是一个地图矢量,而不是一个对象数组。

1 个答案:

答案 0 :(得分:0)

看一下(source clojure.set/index)的灵感。

(def props {:eyes "brown", :age "20"})

(def people #{{:eyes"brown", :age "20", :name "Dick"}
              {:eyes "green", :age "30", :name "Tom"}
              {:eyes "blue", :age "20", :name "Sally"}
              {:eyes "brown", :age "20", :name "Harry"}})

((clojure.set/index people (keys props)) props)
;=> #{{:eyes "brown", :age "20", :name "Harry"} 
      {:eyes "brown", :age "20", :name "Dick"}}