[Immutable.js] Transforming immutable Data with Reduce

Source: Internet
Author: User

Immutable.js Iterables offer the Reduce () method, a powerful and often misunderstood functional operator on which map (), F Ilter (), groupBy (), etc. is built. The concept is simple:reduce transforms your iterable to something else, that's all. The name is misleading as the actually "reduce" anything. Let's replicate the GroupBy () and filter () methods with reduce to illustrate how it works.

Assume you has a list to Todos and each todo with a "completed" Prop:

GroupBy () Like:

Const TODOS =Immutable.list ([{ID:1, Title:"Immutable.js", Completed:true}, {ID:2, Title:"RxJS", Completed:false}, {ID:3, Title:"Reactjs", Completed:false}]); const Groupedtodos= Todos.reduce (ACC, curr) = ={let key= curr.completed? "Completed": "Incompleted"; //Initial value is a immutable Map object, so use Get ("completed") to get the Immutable.list () and then push the Curr Val UE into ITLet list =Acc.get (key). push (Curr); //immutable return a new list from last push, so we need to set this list to the initial value  returnacc.set (key, list); }, Immutable.map ({"Completed": Immutable.list (), "incompleted": Immutable.list ()})); Console.log (Groupedtodos.get ("incompleted"). Get (1). title);//"Reactjs"

Filter () Like:

// Get all imcompleted todosconst FILTEREDTODOS = Todos.reduce ((ACC, curr) +=    {if(!  curr.completed) {     = Acc.push (curr);  }     return acc;}, Immutable.list ()); Console.log (Filteredtodos.get (//  "Reactjs"

[Immutable.js] Transforming immutable Data with Reduce

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.