你可能不需要在 JavaScript 使用 switch 語句!
本文轉(zhuǎn)載自微信公眾號「大遷世界」,轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號。
沒有 switch 就沒有復(fù)雜的代碼塊
switch很方便:給定一個表達(dá)式,我們可以檢查它是否與一堆case子句中的其他表達(dá)式匹配??紤]以下示例:
- const name = "Juliana";
- switch (name) {
- case "Juliana":
- console.log("She's Juliana");
- break;
- case "Tom":
- console.log("She's not Juliana");
- break;
- }
當(dāng) name 為**“Juliana”**時,我們將打印一條消息,并立即中斷退出該塊。在switch函數(shù)內(nèi)部時,直接在 case 塊使用 return,就可以省略break。
當(dāng)沒有匹配項(xiàng)時,可以使用 default 選項(xiàng):
- const name = "Kris";
- switch (name) {
- case "Juliana":
- console.log("She's Juliana");
- break;
- case "Tom":
- console.log("She's not Juliana");
- break;
- default:
- console.log("Sorry, no match");
- }
switch在 Redux reducers 中也大量使用(盡管Redux Toolkit簡化了樣板),以避免產(chǎn)生大量的if??紤]以下示例:
- const LOGIN_SUCCESS = "LOGIN_SUCCESS";
- const LOGIN_FAILED = "LOGIN_FAILED";
- const authState = {
- token: "",
- error: "",
- };
- function authReducer(state = authState, action) {
- switch (action.type) {
- case LOGIN_SUCCESS:
- return { ...state, token: action.payload };
- case LOGIN_FAILED:
- return { ...state, error: action.payload };
- default:
- return state;
- }
- }
這有什么問題嗎?幾乎沒有。但是有沒有更好的選擇呢?
從 Python 獲得的啟示
來自 Telmo 的這條 Tweet引起了我的注意。他展示了兩種“switch”風(fēng)格,其中一種非常接近Python中的模式。
Python 沒有開關(guān),它給我們一個更好的替代方法。首先讓我們將代碼從 JavaScript 移植到Python:
- LOGIN_SUCCESS = "LOGIN_SUCCESS"
- LOGIN_FAILED = "LOGIN_FAILED"
- auth_state = {"token": "", "error": ""}
- def auth_reducer(state=auth_state, action={}):
- mapping = {
- LOGIN_SUCCESS: {**state, "token": action["payload"]},
- LOGIN_FAILED: {**state, "error": action["payload"]},
- }
- return mapping.get(action["type"], state)
在 Python 中,我們可以使用字典來模擬switch 。dict.get() 可以用來表示 switch的 default 語句。
當(dāng)訪問不存在的key時,Python 會觸發(fā)一個 KeyError 錯誤:
- >>> my_dict = {
- "name": "John",
- "city": "Rome",
- "age": 44
- }
- >>> my_dict["not_here"]
- # Output: KeyError: 'not_here'
.get()方法是一種更安全方法,因?yàn)樗粫l(fā)錯誤,并且可以為不存在的key指定默認(rèn)值:
- >>> my_dict = {
- "name": "John",
- "city": "Rome",
- "age": 44
- }
- >>> my_dict.get("not_here", "not found")
- # Output: 'not found'
因此,Pytho n中的這一行:
- return mapping.get(action["type"], state)
等價于 JavaScript中的:
- function authReducer(state = authState, action) {
- ...
- default:
- return state;
- ...
- }
使用字典的方式替換 switch
再次思考前面的示例:
- const LOGIN_SUCCESS = "LOGIN_SUCCESS";
- const LOGIN_FAILED = "LOGIN_FAILED";
- const authState = {
- token: "",
- error: "",
- };
- function authReducer(state = authState, action) {
- switch (action.type) {
- case LOGIN_SUCCESS:
- return { ...state, token: action.payload };
- case LOGIN_FAILED:
- return { ...state, error: action.payload };
- default:
- return state;
- }
- }
如果不使用 switch 我們可以這樣做:
- function authReducer(state = authState, action) {
- const mapping = {
- [LOGIN_SUCCESS]: { ...state, token: action.payload },
- [LOGIN_FAILED]: { ...state, error: action.payload }
- };
- return mapping[action.type] || state;
- }
這里我們使用 ES6 中的計算屬性,此處,mapping的屬性是根據(jù)兩個常量即時計算的:LOGIN_SUCCESS 和 LOGIN_FAILED。屬性對應(yīng)的值,我們這里使用的是對象解構(gòu),這里 ES9((ECMAScript 2018)) 出來的。
- const mapping = {
- [LOGIN_SUCCESS]: { ...state, token: action.payload },
- [LOGIN_FAILED]: { ...state, error: action.payload }
- }
你如何看待這種方法?它對 switch 來說可能還能一些限制,但對于 reducer 來說可能是一種更好的方案。
但是,此代碼的性能如何?
性能怎么樣?
switch 的性能優(yōu)于字典的寫法。我們可以使用下面的事例測試一下:
- console.time("sample");
- for (let i = 0; i < 2000000; i++) {
- const nextState = authReducer(authState, {
- type: LOGIN_SUCCESS,
- payload: "some_token"
- });
- }
- console.timeEnd("sample");
測量它們十次左右,
- for t in {1..10}; do node switch.js >> switch.txt;done
- for t in {1..10}; do node map.js >> map.txt;done