Switch statement vs Object Search
Thu Apr 08 2021 08:01:31 GMT+0000 (Coordinated Universal Time)
Saved by
@Pepe
#javascript
function handleSuccess(){}
function handleUnauthorized(){}
function handleNotFound(){}
function handleUnknownError(){}
const status = 200;
// Switch statement
switch (status) {
case 200:
handleSuccess()
break
case 401:
handleUnauthorized()
break
case 404:
handleNotFound()
break
default:
handleUnknownError()
break
}
// Equivalent using object key search in O(1) time
const hashmap = {
200: handleSuccess,
401: handleUnauthorized,
404: handleNotFound,
default: handleUnknownError
};
const hashmapResult = hashmap.hasOwnProperty(status) ? hashmap[status] : hashmap.default;
console.info(hashmapResult());
content_copyCOPY
https://harsh-patel.medium.com/collection-of-javascript-snippets-728b2565793b
Comments