Ramda compose 会抛出过滤器/映射错误

问题描述 投票:0回答:1

我正在通过重写一个函数来学习 ramda,该函数解析字符串数组中括号内的数字。当我将其编写为单个撰写函数时,注释行和

filter
map
行都会引发错误:

Cannot read properties of undefined (reading 'fantasy-land/filter')

然而,当我将它们编写为两个不同的撰写函数时,它们工作得很好。

匹配/第 n 个组合返回

[ '123', '456', '789' ]

当我尝试调试时,看起来 R.filter 和 R.map 正在对字符串的各个字符进行操作,而不是对 R.nth 返回的每个元素进行操作。

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]

不工作:

const extractNumbersInParenthesesFilterAndConvert = R.compose(
  R.map(Number), // errors
  R.filter(Boolean), // errors
  R.nth(1),
  R.match(/\((\d+)\)$/)
);

// Function to process an array of strings and return the extracted numbers
const extractNumbersFromStrings = R.map(extractNumbersInParenthesesFilterAndConvert);

const inputArray = [
  'Some text (123)',
  'Another string (456)',
  'No numbers here',
  'Last string (789)',
];

let result = extractNumbersFromStrings(inputArray);

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.29.0/ramda.min.js"></script>

工作:

const extractNumbersInParentheses = R.compose(
  // R.map(Number), // errors
  // R.filter(Boolean), // errors
  R.nth(1),
  R.match(/\((\d+)\)$/)
);

const filterAndConvert = R.compose(
  R.map(Number),
  R.filter(Boolean)
);

// Function to process an array of strings and return the extracted numbers
const extractNumbersFromStrings = R.map(extractNumbersInParentheses);

const inputArray = [
  'Some text (123)',
  'Another string (456)',
  'No numbers here',
  'Last string (789)',
];

let result = extractNumbersFromStrings(inputArray);
result = filterAndConvert(result)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.29.0/ramda.min.js"></script>

ramda.js
1个回答
0
投票

Compose 是从右到左的,您需要反转函数数组:

const extractNumbersInParenthesesFilterAndConvert = R.compose(
  R.match(/\((\d+)\)$/),
  R.nth(1),
  R.filter(Boolean),
  R.map(Number)
); 
© www.soinside.com 2019 - 2024. All rights reserved.