经过位掩码解决不定参数问题

某年某月某一天,产品提了个需求:在用户提交信息到服务端的时候,前端须要把全部数据所有转为大写。what?首先想到的是在输入框blur的时候,手动把信息转为大写。打开页面,定睛一看百十来个输入框,难道每个输入框都要去加相似的转换大写的逻辑吗?css

这个时候,能够想到经过css的属性text-transform来设置页面显示的大小写。设置输入框的css为text-transform:uppercase,以保证用户看到的所有大写的样式,而后再提交的时候再进行数据的遍历处理。前端

1. text-transform指定文本的大写

input{
    text-transform: uppercase
}
复制代码

2. 批量处理每项数据

要批量处理每一项数据,其实就是遍历。立刻想到的就是深拷贝,是的,只须要在深拷贝赋值的时候,多加一项数据处理便可。算法

2. 1深拷贝函数的实现

首先咱们须要实现一个深拷贝的函数,那咱们能够直接利用递归的方式来实现设计模式

// 经过递归遍历
function isObject(obj) {
    return typeof obj === 'object' && obj != null
}
function handleTraversal(source, cache = new WeakMap()) {
    if (!isObject(source)) {
        return source
    }

    if (cache.has(source)) {
        return cache.get(source)
    }

    const target = Array.isArray(source) ? [] : {}

    cache.set(source, target)

    for(let key in source) {
        let _sourceItem = source[key]
        
        if (source.hasOwnProperty(key)) {
            if (isObject(_sourceItem)) {
                target[key] = handleTraversal(_sourceItem, cache)
            } else {
                target[key] = _sourceItem
            }
        }
    }

    return target
}
复制代码

固然,经过cache能够解决循环引用问题,可是仍是会存在爆栈的问题,能够经过广度遍历(栈)来实现。缓存

2.2 自动转为大写的实现

在遍历数据过程当中,只需对非对象的数据进行进一步的转换处理。即增长一个处理大写的函数:函数

function transformToUpperCase(str) {
    return typeof str === 'string' ? str.toUpperCase() : str
}
// 增长toUpper参数
function handleTraversal(source, cache = new WeakMap(), toUpper) {
    ...
    
    if (isObject(_sourceItem)) {
      target[key] = handleTraversal(_sourceItem, cache, toUpper)
    } else {
      target[key] = toUpper === true ? transformToUpperCase(_sourceItem) : _sourceItem
    }
    
    ...
}
复制代码

大功告成!!! 过了一天,需求又来了,不只要大写,还须要把多个连续空格转为单个空格。测试

2.3 多个空格转为单个空格的实现

继续增长处理函数:优化

function moreSpaceToSingleSpace(str) {
    return str.replace(/\s+/g, ' ')
}
function handleTraversal(source, cache = new WeakMap(), toUpper, replaceMoreSpace) {
    ...
    if (isObject(_sourceItem)) {
        target[key] = handleTraversal(_sourceItem, cache, toUpper, replaceMoreSpace)
    } else {
        if (typeof _sourceItem === 'string') {
            if (toUpper === true) {
              _sourceItem = transformToUpperCase(_sourceItem)
            }
        
            if (replaceMoreSpace === true) {
              _sourceItem = moreSpaceToSingleSpace(_sourceItem)
            }
        
            target[key] = _sourceItem
          } else {
            target[key] = _sourceItem
          }
        }
    } 
    ...
复制代码

长舒一口气,搞定!!! 那若是哪天又来个需求,要......,🤔️️️️🤔️️️️🤔️️️️,那岂不是又要加一个参数,而且在其余地方调用的时候,而且只是转换空格,那还要去多传一个toupper=false,而且依次递增,......,想都不敢想,接下来会发生什么。ui

咱们能够想一下,是否有一个值就能够代替多种状况的这种方法呢?那接下来,咱们引入位运算,来解决这个问题。spa

3. 经过位掩码实现

3.1 位掩码概述

按位操做符(Bitwise operators) 将其操做数(operands)看成32位的比特序列(由01组成),而不是十进制、十六进制或八进制数值。例如,十进制数9,用二进制表示则为1001。按位操做符操做数字的二进制形式,可是返回值依然是标准的JavaScript数值。

3.1.1 按位逻辑操做符

首先咱们来看一下JavaScript中有哪些按位操做符:

  • 按位与(AND)

只有两个操做数相应的比特位都是1时,结果才为1,不然为0

9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
复制代码
  • 按位或(OR)

只有两个操做数相应的比特位至少有一个为1时,结果就为1,不然为0

9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
复制代码
  • 按位异或(XOR)

只有两个操做数相应的比特位有且只有一个为1时,结果就为1,不然为0

9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 | 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
复制代码
  • 按位非(NOT) 反转操做数的比特位,即0变成11变成0
9 (base 10) = 00000000000000000000000000001001 (base 2)
               --------------------------------
    ~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
复制代码

更多的按位操做符的具体信息,请查看MDN

那么接下来,咱们如何经过按位运算符来实现上面的问题呢?首先,能够发现按位运算符是基于二进制的,而且运算过程是和1有很大关系,那咱们彻底能够以只有一位为1的值表示不一样的处理方式,即:

  • 按位或表明的就是多种处理方式
  • 按位与来判断是否包含当前处理方式

3.2 位掩码具体实现

  1. 将不一样的处理方式转为特殊的数字表示(转为二进制时有且只有一位为1
const TO_UPPER = 1;
const REPLACE_MORE_SPACE = 2;
const TRIM_SPACE = 4;
复制代码
  1. 修改遍历函数结构
function handleTraversal(source, cache = new WeakMap(), bitmask) {
    // 获取处理方式
    const isUpper = bitmask & TO_UPPER;
    const isReplaceMoreSpace = bitmask & REPLACE_MORE_SPACE;
    const isTrimSpace = bitmask & TRIM_SPACE;
    
    if (isObject(_sourceItem)) {
        target[key] = handleTraversal(
            _sourceItem,
            ...[...arguments].slice(1)
        );
    } else {
        if (typeof _sourceItem === "string") {
            if (isUpper) {
                _sourceItem = transformToUpperCase(_sourceItem);
            }
            
            if (isReplaceMoreSpace) {
                _sourceItem = moreSpaceToSingleSpace(_sourceItem);
            }
            
            if (isTrimSpace) {
                _sourceItem = trimSpace(_sourceItem);
            }
            
            target[key] = _sourceItem;
        } else {
            target[key] = _sourceItem;
        }
    }
}
复制代码
// 测试
let a = {
    a: "aa a",
    b: {
      c: " ee ",
      d: null,
      f: undefined
    }
  };

  let b = handleTraversal(a, new WeakMap(), TO_UPPER | TRIM_SPACE);

  console.log(a);
  console.log(b);
复制代码

到这里,咱们已经不用在之后用到这个函数的时候,还要去传入多个参数,各类truefalse,经过位掩码的方式咱们已经能够解个没必要要的参数传递。那既然到这里了,咱们再回头看一下这个函数,是否还有其余的问题呢?

假如后面又加了一个参数以及一个处理函数,又要去更改函数内部的结构,违背了设计模式的开放—封闭原则。那么接下来,咱们能够经过策略模式进一步来优化。

4. 经过策略模式优化

熟悉策略模式的同窗,确定都知道经过策略模式,不只能够有效地避免多重条件选择语句,还提供了对开放—封闭原则的完美支持,将算法封装在独立的strategy中,使得它们易于切换,易于理解,易于扩展。

4.1. 策略类(strategy)的建立

const strategyProcess = {
    transformToUpperCase: {
        // 对应的二进制中1的位置
        value: TO_UPPER,
        // 对应的处理函数
        fn(str) {
            return str.toUpperCase();
        }
    },
    moreSpaceToSingleSpace: {
        value: REPLACE_MORE_SPACE,
        fn(str) {
            return str.replace(/\s+/g, " ");
        }
    },
    trimSpace: {
        value: TRIM_SPACE,
        fn(str) {
            return str.trim();
        }
    }
};
复制代码

4.2. 遍历函数优化

// 剔除以前的位掩码,改成回调函数,全部处理隔离遍历函数
function handleTraversal( source, cache = new WeakMap(), callback = () => {}
) {
    if (!isObject(source)) {
        return source;
    }

    if (cache.has(source)) {
        return cache.get(source);
    }

    const target = Array.isArray(source) ? [] : {};

    cache.set(source, target);

    for (let key in source) {
        let _sourceItem = source[key];

        if (source.hasOwnProperty(key)) {
            if (isObject(_sourceItem)) {
                target[key] = handleTraversal(
                    _sourceItem,
                    ...[...arguments].slice(1)
                );
            } else {
                if (typeof _sourceItem === "string") {
                    target[key] = callback(_sourceItem);
                } else {
                    target[key] = _sourceItem;
                }
            }
        }
    }

    return target;
}
复制代码

4.3. 回调函数或调用策略类

// 获取处理的方式,来调用处理方式的具体处理函数
const processFn = bitmask => {
    return function () {
        let result = arguments[0];

        Object.values(process).forEach(item => {
            const { value, fn } = item;

            result = bitmask & value ? fn(result) : result;
        });

        return result;
    };
};
复制代码
// 测试2.0
let a = {
    a: "aa a",
    b: {
        c: " ee ",
        d: null,
        f: undefined
    }
};

let b = handleTraversal(
    a,
    new WeakMap(),
    processFn(TO_UPPER | TRIM_SPACE | REPLACE_MORE_SPACE)
);

console.log(a);
console.log(b);
复制代码

4.4. 经过缓存优化策略类的调用

回调函数中,咱们能够看到在handleTraversal遍历函数中,每次调用callback时,都从新筛选策略类,既然这样,能够在首次筛选时进行缓存

const processFn = bitmask => {
    // 因为weakMap的属性必须为对象,因此改成Map
    const cache = new Map();
    return function () {
        let result = arguments[0];

        if (cache.size > 0) {
            Object.values(cache).forEach(fn => {
                result = fn(result);
            });

            return result;
        }

        Object.values(process).forEach(item => {
            const {
                value,
                fn
            } = item;

            if (bitmask & value) {
                result = fn(result);
                cache.set(value, fn);
            }
        });

        return result;
    };
};
复制代码

5. 总结

固然,本文主要是经过基于位运算的方案,来解决这种不定参数的问题。欢迎小伙伴提供更好的解决方案。

针对位运算,工做中确实用到的不多,可是用到它的地方,确实能够达到意想不到的效果,而且其运算效率不只更高,还节省存储空间。同时,位运算的在算法中也能够起到妙趣横生的有趣效果。

相关文章
相关标签/搜索