某年某月某一天,產品提了個需求:在用戶提交信息到服務端的時候,前端須要把全部數據所有轉爲大寫。what?首先想到的是在輸入框blur的時候,手動把信息轉爲大寫。打開頁面,定睛一看百十來個輸入框,難道每個輸入框都要去加相似的轉換大寫的邏輯嗎?css
這個時候,能夠想到經過css的屬性text-transform
來設置頁面顯示的大小寫。設置輸入框的css爲text-transform:uppercase
,以保證用戶看到的所有大寫的樣式,而後再提交的時候再進行數據的遍歷處理。前端
input{
text-transform: uppercase
}
複製代碼
要批量處理每一項數據,其實就是遍歷。立刻想到的就是深拷貝,是的,只須要在深拷貝賦值的時候,多加一項數據處理便可。算法
首先咱們須要實現一個深拷貝的函數,那咱們能夠直接利用遞歸的方式來實現設計模式
// 經過遞歸遍歷
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
能夠解決循環引用問題,可是仍是會存在爆棧的問題,能夠經過廣度遍歷(棧)來實現。緩存
在遍歷數據過程當中,只需對非對象的數據進行進一步的轉換處理。即增長一個處理大寫的函數:函數
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
}
...
}
複製代碼
大功告成!!! 過了一天,需求又來了,不只要大寫,還須要把多個連續空格轉爲單個空格。測試
繼續增長處理函數:優化
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
按位操做符(
Bitwise operators
) 將其操做數(operands
)看成32
位的比特序列(由0
和1
組成),而不是十進制、十六進制或八進制數值。例如,十進制數9
,用二進制表示則爲1001
。按位操做符操做數字的二進制形式,可是返回值依然是標準的JavaScript
數值。
首先咱們來看一下JavaScript
中有哪些按位操做符:
只有兩個操做數相應的比特位都是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)
複製代碼
只有兩個操做數相應的比特位至少有一個爲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)
複製代碼
只有兩個操做數相應的比特位有且只有一個爲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)
複製代碼
0
變成1
,1
變成0
。9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
複製代碼
更多的按位操做符的具體信息,請查看MDN。
那麼接下來,咱們如何經過按位運算符來實現上面的問題呢?首先,能夠發現按位運算符是基於二進制的,而且運算過程是和1
有很大關係,那咱們徹底能夠以只有一位爲1
的值表示不一樣的處理方式,即:
按位或
表明的就是多種處理方式按位與
來判斷是否包含當前處理方式1
)const TO_UPPER = 1;
const REPLACE_MORE_SPACE = 2;
const TRIM_SPACE = 4;
複製代碼
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);
複製代碼
到這裏,咱們已經不用在之後用到這個函數的時候,還要去傳入多個參數,各類true
,false
,經過位掩碼的方式咱們已經能夠解個沒必要要的參數傳遞。那既然到這裏了,咱們再回頭看一下這個函數,是否還有其餘的問題呢?
假如後面又加了一個參數以及一個處理函數,又要去更改函數內部的結構,違背了設計模式的開放—封閉原則
。那麼接下來,咱們能夠經過策略模式
進一步來優化。
熟悉策略模式的同窗,確定都知道經過策略模式
,不只能夠有效地避免多重條件選擇語句
,還提供了對開放—封閉原則
的完美支持,將算法封裝在獨立的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();
}
}
};
複製代碼
// 剔除以前的位掩碼,改成回調函數,全部處理隔離遍歷函數
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;
}
複製代碼
// 獲取處理的方式,來調用處理方式的具體處理函數
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);
複製代碼
在回調函數
中,咱們能夠看到在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;
};
};
複製代碼
固然,本文主要是經過基於位運算
的方案,來解決這種不定參數的問題。歡迎小夥伴提供更好的解決方案。
針對位運算,工做中確實用到的不多,可是用到它的地方,確實能夠達到意想不到的效果,而且其運算效率不只更高,還節省存儲空間。同時,位運算的在算法中也能夠起到妙趣橫生的有趣效果。