zoukankan      html  css  js  c++  java
  • [Ramda] Change Object Properties with Ramda Lenses

    In this lesson we'll learn the basics of using lenses in Ramda and see how they enable you to focus changes on specific properties of an object while keeping your data immutable.

    what 'R.lens' do is able to get or set prop value but keep the object immutable.

    Normally you have 2 ways to use lens:

    1. set up lens: 'lens' + 'prop' + 'assoc';

    After set up you can either get value by using 'R.view';

    Or change a prop by using 'R.set' or 'R.over'.

    2.  Using 'lens' + 'prop' + 'assoc' is a little bit work to do, there is short syntax to do the same thing: 'R.lensProp'.

    const R = require('ramda');
    
    const {view, lens, assoc, prop, set, over, lensProp, toUpper} = R;
    
    const person = {
        firstName: 'Fred',
        lastName: 'Filntstore'
    };
    
    /*
    * What lens does is modify prop value for a given object
    * and keep data immutable.
    * */
    
    const firstNameLens = lens(
        prop('firstName'),
        assoc('firstName')
    );
    const viewFirstName = view(firstNameLens);
    // const result = viewFirstName(person); // Fred
    
    /** Using R.set **/
    const setFirstName = set(firstNameLens);
    const updateFirstName = setFirstName('Zhentian');
    // const result = updateFirstName(person); // { firstName: 'Zhentian', lastName: 'Filntstore' }
    
    /** Using R.over instead of set **/
    const result = over(firstNameLens, toUpper, person);
    
    /** lensProp instead of prop + assoc **/
    const lastNameLens = lensProp('lastName');
    const result2 = over(lastNameLens, toUpper, person); // { firstName: 'Fred', lastName: 'FILNTSTORE' }
    console.log(result);
    console.log(result2);
  • 相关阅读:
    多重背包 HDU2191
    带限制求最小价值的完全背包 HDU1114
    均分背包 HDU1171
    经典01背包问题 HDU2602
    记忆化搜索 POJ1579
    最大递增子序列变形——二维带权值 O(n*n) HDU1069
    最大递增子序列变形——二维 O(n*logn) TOJ4701
    OCJP(1Z0-851) 模拟题分析(六)over
    OCJP(1Z0-851) 模拟题分析(八)over
    OCJP(1Z0-851) 模拟题分析(九)over
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5947338.html
Copyright © 2011-2022 走看看