【发布时间】:2018-03-25 17:29:01
【问题描述】:
我正在学习 Underscore.js 和高阶函数。我遇到了以下问题,我只是卡住了。
我不是在寻找讲义,但与此同时,我没有任何地方可以寻求指导。我希望有人至少为我指明正确的方向。
命令式 vs 函数式到底是什么意思?
在完成“功能性”解决方案时,我什至不知道从哪里开始。
任何有关此主题的有用信息将不胜感激。
请注意:我确实了解 map()、flatten() 和 reduce() 的作用。我只是不知道如何将其应用于这种情况。
我不明白“功能性”的真正含义。我会喜欢任何见解。
var products = [
{
name: 'Sonoma',
ingredients: ['artichoke', 'sundried tomatoes', 'mushrooms'],
containsNuts: false,
},
{
name: 'Pizza Primavera',
ingredients: ['roma', 'sundried tomatoes', 'goats cheese', 'rosemary'],
containsNuts: false,
},
{
name: 'South Of The Border',
ingredients: ['black beans', 'jalapenos', 'mushrooms'],
containsNuts: false,
},
{
name: 'Blue Moon',
ingredients: ['blue cheese', 'garlic', 'walnuts'],
containsNuts: true,
},
{
name: 'Taste Of Athens',
ingredients: ['spinach', 'kalamata olives', 'sesame seeds'],
containsNuts: true,
},
];
// Underscore.js
// Count the ingredient occurence
// IMPERATIVE example:
var ingredientCount = { "{ingredient name}": 0 };
for (i = 0; i < products.length; i += 1) {
for (j = 0; j < products[i].ingredients.length; j += 1) {
ingredientCount[products[i].ingredients[j]] =
(ingredientCount[products[i].ingredients[j]] || 0) + 1;
}
}
expect(ingredientCount['mushrooms')]).toBe(2);
// FUNCTIONAL:
/* chain() together map(), flatten() and reduce() */
var ingredientCount = { "{ingredient name}": 0 };
// ? ? ?
expect(ingredientCount['mushrooms']).toBe(2);
【问题讨论】:
-
您需要先会走路,然后才能跑步。对
map、filter和reduce(它们是标准 JS 数组类型的一部分,不是 Underscore 特定的)有一些基本的了解,将有助于您思考如何解决这个问题一种使用函数式方法的问题。 -
@AsadSaeeduddin 抱歉,我的帖子不清楚。我确实了解
map、filter和reduce的作用。我只是不明白它在这里是如何应用的,以及“功能”的实际含义。 -
见en.wikipedia.org/wiki/Functional_programming。这里的相关性是,您将编写一个函数来执行所示的命令式、基于循环的转换,而不是使用数组组合器和纯函数。
-
例如,“将数组中的每个元素乘以 2”的命令式解决方案是
const newArray = []; for (let i = 0; i < oldArray.length; i++) { newArray.push(oldArray[i] * 2); }。功能解决方案为:const newArray = oldArray.map(i => i * 2).
标签: javascript functional-programming underscore.js imperative-programming