簡體   English   中英

Underscore.js-命令和功能練習

[英]Underscore.js - Imperative & Functional exercise

我正在學習Underscore.js和高階函數。 我遇到了以下問題,我只是被卡住了。

我不是在尋找講義,但與此同時,我沒有任何地方可以尋求指導。 我希望有人至少可以指出正確的方向。

命令式與功能性究竟是什么意思?

對於完成“功能性”解決方案,我什至不知道從哪里開始。

任何有關此主題的有用信息將不勝感激。

請注意:我確實了解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);

您需要將其分解為幾個部分。 首先,您只關心成分,但是products包含大量額外信息,因此請使用map提取成分。

現在,您可以將成分放在一組數組中,但是您只想要一個包含所有成分的大數組,因此可以使用flatten來實現。

現在您要計算成分。 您可以認為這是一系列減少,您有一個具有先前計數的對象,而對於當前項目,您想要增加計數。 這可以通過以空對象開始的reduce來完成。 我將把incrementCount功能的實現留給讀者練習。

const ingredients = _.map(products, p => p.ingredients);
const flatIngredients = _.flatten(ingredients);
const counts = _.reduce(flatIngredients, incrementCount, {});

使用功能代碼,可以將您的數據視為經過一系列轉換,每次轉換都使您更接近目標,而不是一個試圖將所有變異都塞入其中的大循環。

功能性意味着每個被調用的函數都具有返回值,並且通常沒有副作用(“純”)。 這是一種非常適合數據轉換的編程風格。

  • map接受一個數組,並返回一個數組,其中每個項目都已轉換。
  • reduce遍歷數組,始終提供先前返回的值和數組中的下一項,從而計算新值。 可用於計算總和等。
  • flatten使列表列表變成一個列表。

 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, }, ]; const result = products.reduce((allIngredients, item) => allIngredients.concat(item.ingredients), []) .reduce((counts, ingredient) => { counts[ingredient] ? counts[ingredient]++ : (counts[ingredient] = 1); return counts }, {}) console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM