zoukankan      html  css  js  c++  java
  • [Javascript Crocks] Flatten Nested Maybes with `chain`

    Sometimes, we run into situations where we end up with a Maybe within the context of another Maybe. Nested structures like this can get really confusing to work with. In this lesson, we’ll look at an example of this and see how chaincan help us out by flattening the nested Maybe

    As we all know, inside an array return another array is nested array.

    Inside observable return another observable get Observable of Observable.

    The same inside Just return another Just, we get Just of Just:

    const prop = require('crocks/Maybe/prop');
    const propPath = require('crocks/Maybe/propPath');
    
    /**
     * return Maybe type
     */
    const getUser = id =>
        new Promise((resolve, reject) => {
            const result = {
                status: 200,
                body: {
                    id: 1,
                    username: 'tester',
                    email: 'test@gmail.com',
                    address: {
                        street: '111 E. West St',
                        city: 'Anywhere',
                        state: 'PA',
                        postalCode: '19123-4567'
                    }
                }
            }
            resolve(prop('body', result)); // return Just {}
        });
    
    
    const getPostalCode = propPath(['address', 'postalCode']); 
    
    getUser(1)
        .then(user => user.map(getPostalCode)) // map to Just {} --> Just Just '19123-4567'
        .then(console.log); // Just Just "19123-4567"

    Inside getUser function we return a Just type object. Then from propPath, we get Just Just type object. That's why we need flatten it.

    The way to solve the problem is using flat map which is called 'chain' in Crocks.

    getUser(1)
        .then(user => user.chain(getPostalCode).option("not available")) 
        .then(console.log); // "19123-4567"
  • 相关阅读:
    解释DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
    MySQL性能优化
    MySQL中的binlog相关命令和恢复技巧
    保障MySQL安全的14个最佳方法
    MySQL忘记root密码的解决方案
    MySQL利用binlog来恢复数据库
    MySQL命令mysqldump参数大全
    MySQL REPLACE替换输出
    MySQL -A不预读数据库信息(use dbname 更快)
    MySQL 慢查询配置
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9026521.html
Copyright © 2011-2022 走看看