一個performance監(jiān)控上報的需求割岛,其中涉及一個方法是通過文件擴展名和resource的initiatorType來獲取資源的實際文件類型
當然是先看看類似需求在同性交友網(wǎng)站上有沒有
找到一處
performance-bookmarklet
看這段代碼
helper.getFileType = function(fileExtension, initiatorType){
if(fileExtension){
switch(fileExtension){
case "jpg" :
case "jpeg" :
case "png" :
case "gif" :
case "webp" :
case "svg" :
case "ico" :
return "image";
case "js" :
return "js"
case "css":
return "css"
case "html":
return "html"
case "woff":
case "woff2":
case "ttf":
case "eot":
case "otf":
return "font"
case "swf":
return "flash"
case "map":
return "source-map"
}
}
if(initiatorType){
switch(initiatorType){
case "xmlhttprequest" :
return "ajax"
case "img" :
return "image"
case "script" :
return "js"
case "internal" :
case "iframe" :
return "html" //actual page
default :
return "other"
}
}
return initiatorType;
};
拿來我就用了……
這段代碼的作用是判斷傳入的擴展名和追蹤類型存在 有一個存在即進入推斷過程,推斷過程是用一堆switch case寫的,當時copy的時候也是懶搏明,沒想過改造下……
當然mr的時候被老大給點了怜森,點的一點都不冤……然后我就寫了個如下代碼……
image.png
在使用時
const fileType = fileTypeMap[擴展名] || fileTypeMap[追蹤類型] || 'other'';
這是我這個腦子能想到的……
然后老大寫了下他瞬間實現(xiàn)的(這可能和他從小愛吃肉有關系 笑)
const typeMapList = [{
originType: ['xmlhttprequest'],
targetType: 'ajax',
}, {
originType: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico', 'img' ],
targetType: 'image',
}, {
originType: ['js', 'script' ],
targetType: 'js',
}, {
originType: ['css'],
targetType: 'css',
}, {
originType: ['html', 'internal', 'iframe' ],
targetType: 'html',
}, {
originType: ['woff', 'woff2', 'ttf', 'eot', 'otf' ],
targetType: 'font',
}, {
originType: ['swf'],
targetType: 'flash',
}, {
originType: ['map'],
targetType: 'source-map',
}];
function getFileType(type) {
const typeMap = typeMapList.find(map => map.originType.includes(type));
return typeMap ? typeMap.targetType : 'other';
}
const fileType = getFileType(追蹤類型 || 擴展名);
從此處代碼可以看出來我的幾個明顯錯誤
- 拿來主義 對交友網(wǎng)站的代碼沒有考慮
- 抽象意識局限 哪怕改了switch-case結(jié)構(gòu) 卻依舊沒有意識到類型的匹配和擴展
改進方法
- 對別人寫的代碼不能懶copy 其實就是懶的(屎一樣的switch-case當然看到了??
- 想清楚要的功能是什么畏鼓,可以抽象出哪幾個部分拘悦,是否滿足方法/組件設計的原則
- 多吃些核桃