在 Immutable.js 中深入查找

Deep find in Immutable.js

我希望能够在 Immutable.js 中找到深层嵌套值的 keyPath。我如何填写此功能 deepFind 以获得我想要的内容?

const map = Immutable.fromJS({
    a: { 
        a1: 1,
        b1: 2
    },
    b: {
        b1: 3
        b2: 4,
        b3: 5
    }
});

function deepFind(map, value) {
    /* ??? */
}

deepFind(map, 4); // returns ['b', 'b2']

看起来没有任何 built-in 方法可以做到这一点,所以我决定进行 depth-first 搜索。我使用 .toKeyedSeq() 搜索具有相同代码的所有 collection 类型。

注意:如果您的 collection 包含自己,此函数将永远挂起。

import Immutable from 'immutable';

function deepFind(root, value, path = Immutable.List()) {
  if (root === value) {
    return path;
  }

  if (!Immutable.isImmutable(root)) {
    // this is a leaf node, and it's not the value we want.
    return undefined;
  }

  for (const [key, child] of root.toKeyedSeq()) { 
    const result = deepFind(child, value, path.push(key));
    if (result) {
      return result;
    }
  }

  // no path is found
  return undefined;
}