如何解决 Ramda reduce 函数 (javascript) 的不正确 return 结果

How to resolve incorrect return result from Ramda reduce function (javascript)

我有一个数据结构,我称之为 'spec',它看起来像这样:

const spec = {
  command: {
    name: 'name',
    description: 'description',
    alias: 'alias',
    arguments: '_children/Arguments'
  },
  arguments: {
    name: 'name',
    alias: 'alias',
    optional: 'optional',
    description: 'description'
  }
};

因此 commandarguments 中的元素是映射到路径的属性。最好的例证是spec.command.arguments。我需要做的是将其转换为另一个具有相同形状的对象,但路径被转换为 Ramda 镜头(使用 R.lensPath)。

所以从概念上讲,这被翻译成这样:

const spec = {
  command: {
    name: lens('name'),
    description: lens('description'),
    alias: lens('alias'),
    arguments: lens('_children/Arguments')
  },
  arguments: {
    name: lens('name'),
    alias: lens('alias'),
    optional: lens('optional'),
    description: lens('description')
  }
};

以上不是字面意思,是伪结构。例如 lens('_children/Arguments') 仅表示使用 Ramda lensPath 构建的镜头。

所以这是我的代码:

const spec = {
  command: {
    name: 'name',
    description: 'description',
    alias: 'alias',
    arguments: '_children/Arguments'
  },
  arguments: {
    name: 'name',
    alias: 'alias',
    optional: 'optional',
    description: 'description'
  }
};

function lensify (spec) {
  const result = R.pipe(
    R.toPairs,
    R.reduce((acc, pair) => {
      const field = pair[0];
      const path = pair[1];
      const lens = R.compose(
        R.lensPath,
        R.split('/')
      )(path);

      acc[field] = lens; // Is there something wrong with this, if so what?
      return acc;
    }, { dummy: '***' }) // list of pairs passed as last param here
  )(spec);

  // The following log should show entries for 'name', 'description', 'alias' ...
  console.log(`+++ lensify RESULT: ${JSON.stringify(result)}`);
  return result;
}

function makeLenses (spec) {
  const result = {
    command: lensify(spec.command),
    arguments: lensify(spec.arguments)
  };

  return result;
}

makeLenses(spec);

我认为失败的关键点在 reducer 函数内部,returns 更新的累加器 (acc[field] = lens;)。由于某种我无法理解的原因,这个分配正在丢失,并且在每次迭代中都没有正确填充累加器。从代码示例中可以看出,传递给 reduce 的初始值是一个具有单个 dummy 属性 的对象。减少的结果错误地只是这个单一的虚拟值,而不是所有具有各自 Ramda 镜头的字段。

然而,真正让你吃不消的是 Ramda repl 中完全相同的代码 运行 表现出不同的行为,请参阅 repl 中的这段代码:Ramda code

我是运行节点版本10.13.0

Repl 代码产生的结果是这样的:

{
  'arguments': {
    'alias': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'description': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'dummy': '***',
    'name': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'optional': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    }
  },
  'command': {
    'alias': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'arguments': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'description': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    },
    'dummy': '***',
    'name': function (r) {
      return function (e) {
        return z(function (t) {
          return n(t, e)
        }, r(t(e)))
      }
    }
  }
}

如您所见,结果看起来有点复杂,因为每个 属性 的值都是由 lensProp 创建的镜头。

这与下面的对比(注意命令和参数的顺序是相反的,但这不应该很重要):

{
  'command': {
    'dummy': '***'
  },
  'arguments': {
    'dummy': '***'
  }
}

在我的单元测试中返回。

我已经在这上面浪费了大约 2 天时间,现在我承认失败了,所以希望有人能对此有所启发。干杯。

这显示了我能想象到的最简单的输出用法,将 view 映射到镜头上的普通物体上。它似乎在 REPL 和 Node 10.13.0 中都能正常工作:

const {map, pipe, split, lensPath, view} = ramda  

const makeLenses = map ( map ( pipe ( split ('/'), lensPath )))

const applyLensSpec = (lensSpec) => (obj) => 
  map ( map ( f => view (f, obj) ), lensSpec)

const spec = {command: {name: "name", description: "description", alias: "alias", arguments: "_children/Arguments"}, arguments: {name: "name", alias: "alias", optional: "optional", description: "description"}};

const myTransform = applyLensSpec(
  makeLenses(spec),
)

const testObj =   {
  name: 'foo', 
  alias: 'bar', 
  description: 'baz', 
  optional: false, 
  _children: {
    Arguments: ['qux', 'corge']
  }
}

console .log (
  myTransform (testObj)
)
<script src="https://bundle.run/ramda@0.26.1"></script>

此 post 的附录,为了符合 Scott 所说,此 post 的原因是 JSON.stringify 的不足,这实际上是这个故事的寓意;不要总是相信 JSON.stringify 的输出。这是一个证实这一点的测试用例:

  context('JSON.stringify', () => {
    it.only('spec/lensSpec', () => {
      const spec = {
        command: {
          name: 'name',
          description: 'description',
          alias: 'alias',
          arguments: '_children/Arguments'
        },
        arguments: {
          name: 'name',
          alias: 'alias',
          optional: 'optional',
          description: 'description'
        }
      };

      const makeLensSpec = R.map(R.map(R.pipe(
        R.split('/'),
        R.lensPath
      )));

      const lensSpec = makeLensSpec(spec);
      console.log(`INPUT spec: ${JSON.stringify(spec)}`);
      // The following stringify does not truly reflect the real value of lensSpec.
      // So do not trust the output of JSON.stringify when the value of a property
      // is a function as in this case where they are the result of Ramda.lensProp.
      //
      console.log(`RESULT lensSpec: ${JSON.stringify(lensSpec)}`);
      const rename = {
        'name': 'rename',
        'alias': 'rn',
        'source': 'filesystem-source',
        '_': 'Command',
        'describe': 'Rename albums according to arguments specified.',
        '_children': {
          'Arguments': {
            'with': {
              'name': 'with',
              '_': 'Argument',
              'alias': 'w',
              'optional': 'true',
              'describe': 'replace with'
            },
            'put': {
              'name': 'put',
              '_': 'Argument',
              'alias': 'pu',
              'optional': 'true',
              'describe': 'update existing'
            }
          }
        }
      };

      // NB, if the output of JSON.stringify was indeed correct, then this following
      // line would not work; ie accessing lensSpec.command would result in undefined,
      // but this is not the case; the lensSpec can be used to correctly retrieve the
      // command name.
      //
      const name = R.view(lensSpec.command.name, rename);
      console.log(`COMMAND name: ${name}`);
    });
  });

注意的日志语句是:

console.log(INPUT spec: ${JSON.stringify(spec)});

显示的是:

INPUT spec: {"command":{"name":"name","description":"description","alias":"alias","arguments":"_children/Arguments"},"arguments":{"name":"name","alias":"alias","optional":"optional","description":"description"}}

console.log(RESULT lensSpec: ${JSON.stringify(lensSpec)});

这是错误的(lensSpec 包含其值是字符串化无法显示的函数的属性,因此完全遗漏了它们,给出了不正确的表示:

RESULT lensSpec: {"command":{},"arguments":{}}

console.log(COMMAND name: ${name});

这按预期工作:

COMMAND name: rename

注意:我刚发现这个:Why doesn't JSON.stringify display object properties that are functions?