【问题标题】:How to resolve incorrect return result from Ramda reduce function (javascript)如何解决 Ramda reduce 函数的错误返回结果(javascript)
【发布时间】:2019-10-17 03:55:23
【问题描述】:

我有一个称为“规范”的数据结构,如下所示:

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函数内部,它返回更新的累加器(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 天的时间,现在承认失败了,所以希望有人能对此有所了解。干杯。

【问题讨论】:

  • 我真的不确定你的问题是什么。 REPL 中的结果对我来说是正确的。 (请注意,JSON.stringify 不会为您提供有关函数属性的有用结果。)您返回一个具有 argumentscommand 属性的对象,每个属性都是包含 namealiasargumentsoptional属性,每人拿着一个镜头。这不是你想要的吗?
  • 请注意,只要您实际上并不想要 dummy 属性,您可以将lensify 更简单地写为const lensify = map(pipe(split('/'), lensPath))
  • 您的最终 REPL 结果未包含在 JSON.stringify 中。它使用 REPL 更复杂的显示功能。 JSON.stringify(makeLenses(spec)) //=> "{\"command\":{\"dummy\":\"***\"},\"arguments\":{\"dummy\":\"***\"}}"
  • 另外,您可以跳过 lensifyconst makeLenses = map(map(pipe(split('/'), lensPath))),假设您要将其应用于规范的所有元素。
  • 实际上,我意识到我在我的一些客户端代码中做了一个很大的嘘声,这导致了我在尝试访问镜头时看到的未定义。它现在可以工作并产生与 Repl 相同的结果。谢谢你帮助斯科特。我将在我的最终代码中使用您更精简的版本,尽管我已经知道我将对其进行精简。我不知道的一件事是 repl 增强的显示能力,这让我感到困惑。我使用的 console.log/JSON.stringify 语句没有显示 Repl 所做的镜头属性,这让我陷入了困境!。

标签: javascript functional-programming reduce ramda.js


【解决方案1】:

这显示了我能想象到的最简单的输出用法,将镜头上的view 映射到一个普通对象。它似乎在 REPL、sn-p 和 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>

【讨论】:

  • 太棒了,斯科特,干杯。我的问题是 2 倍,此帖子中未显示的不正确客户端代码以及对 JSON.stringify 的混淆以及这与 Ramda repl 有何不同
  • REPL 试图比JSON.stringify 更有帮助。这是我第一次听说由此引起的混乱,但我当然可以理解它是如何发生的!
  • 好吧,我敢肯定,在时间充裕和获得更多知识的情况下,我敢肯定,我肯定会证明我误解了什么或做错了什么。这都是我的 JavaScript 旅程的一部分。谢谢
【解决方案2】:

这篇文章的附录,为了符合 Scott 所说的,这篇文章的原因是 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 包含其值是 stringify 无法显示的函数的属性,因此完全错过了它们,给出了不正确的表示:

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

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

这按预期工作:

COMMAND name: rename

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

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 2016-10-03
    • 2018-05-04
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多