Map()对象实现文件处理器

81 阅读1分钟

1.new Map()用法

let priceArr = [    ['car',30000],
    ['house',50000],
    ['salary',20],
    ['dream',200]
]
const getPrice = (data, name) => {
       return new Map(data).get(name)
}

console.log(getPrice(priceArr,'house')) // 打印: 50000

2.文件处理器

class fileHelper{
    constructor(){ // 实例化对象时会调用的钩子
        // 声明一个map对象
        this.myFileType = new Map()
        // 调用这个Map对象的初始化方法
        this.initMap()
    }
    initMap(){
        // image
        this.myFileType.set('png','image/png')
        this.myFileType.set('jpg','image/jpeg')
        this.myFileType.set('jpeg','image/jpeg')
        this.myFileType.set('gif','image/gif')
        // text
        this.mimeTypes.set('json', 'application/json');
        this.mimeTypes.set('txt', 'text/plain');
    }
    // 获取文件类型方法
    getMineType(extension){
        return this.mineTypes.get(extension)
    }
    
    
    // 获取后缀方法
    getExtension(url){
        return url.substr(url.lastIndexOf('.') + 1) 
        // str.substr(x,y) 从x的后一位开始算,截取y位字符
        // str.lastIndexOf('string') 得到字符在字符串最后出现的index
    }
    
    // 返回文件方法
    requestResource(uri, options){
        // 获取后缀
        let extension = this.getExtension(uri)
        // 将后缀传入map,遍历出返回值
        let myType = this.myFileType(extension)
        
        let responseType = options && options.responseType ? options.responseType.toLowerCase : undefined
        if(responseType) return this.requestFile(uri,options)
        
        if(myType){ // 有处理方法的文件类型
        // 当myType为image时,调用并返回创建Image方法
        // arr.match(/xxx/g): 返回字符串中所有含有xxx的字符,不区分大小写,有g就匹配到字符串结束,返回一个数组,没有g则只匹配一次,一旦匹配到就返回一个字符串,匹配不到就返回Null
            // 判断每种文件格式,调用不同的处理文件返回方法
            if(myType.match('image')) return this.createImageFromURL(uri)
            else if (mimetype.match('binary')) return this.createArrayBufferFromURL(uri);
            else if (mimetype.match('json')) return this.createJSONFromURL(uri);
            else if (mimetype.match('text')) return this.requestFile(uri);
        }
        // 如果是没有处理方法的文件类型
        return this.requestFile(uri);
    }
    
    // 每种文件格式的处理方法
    ....
    
    
}
// 导出构造类
export default FileHelper