通过生成相同/相似形状(不同类型)的数据结构来模拟不变性

时间:2019-07-13 07:48:18

标签: javascript functional-programming immutability

为了避免模仿不变性,我经常经常得到具有相同形状的不同数据结构,以免改变现有数据结构。为了更容易区分嵌套数据结构的各个层并使它们彼此保持一致,我将它们包装为仅用作“语义包装器”的类型。这是简化的模式:

const ListX = xs =>
  ({runListX: xs, [Symbol.toStringTag]: "ListX"});

const ListY = xs =>
  ({runListY: xs, [Symbol.toStringTag]: "ListY"});

const foo = [ListX([ListY([1, 2, 3]), ListY([4, 5, 6])])];

// later I gather more data that is related to foo but instead of
// altering foo I just create a new data structure

const bar = [ListX([ListY(["a", "b", "c"]), ListY(["d", "e", "f"])])];

const fold = f => init => xs =>
  xs.reduce((acc, x, i) => f(acc) (x, i), init);

const combining = foo => bar =>
  fold(acc1 => (tx, i) =>
    fold(acc2 => (ty, j) =>
      fold(acc3 => (x, k) => {
        const y = bar[i].runListX[j].runListY[k];
        return (acc3.push(x + y), acc3)
      }) (acc2) (ty.runListY)) (acc1) (tx.runListX)) ([]) (foo);

console.log(
  combining(foo) (bar)); // ["1a","2b","3c","4d","5e","6f"]

它适用于具有1000行代码的程序。但是,我想知道它是否仍适用于更大的代码库。这种方法的长期缺点是什么(可以与像immutable.js之类的库获得的真正不变性相比)?这种方法/模式甚至有名称吗?

请注意,我知道对于SO这样的问题可能太广泛了。尽管如此,这还是困扰着我。

0 个答案:

没有答案