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

450 阅读8分钟

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

这个时候,可以想到通过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,并且依次递增,......,想都不敢想,接下来会发生什么。

我们可以想一下,是否有一个值就可以代替多种情况的这种方法呢?那接下来,我们引入位运算,来解决这个问题。

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. 总结

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

针对位运算,工作中确实用到的很少,但是用到它的地方,确实可以达到意想不到的效果,并且其运算效率不仅更高,还节省存储空间。同时,位运算的在算法中也可以起到妙不可言的有趣效果。