《前端面试题》- 编程题- 提供辅助类(缓存)

假如有一个接口getUsersById(userId),返回用户信息的json;要求getUsersById能缓存用户信息,即同样的userId请求仅向服务器发送一次,其余从内存中获取,以提高效率。高阶要求:假设有getUsersById, getShoolInfoById, getDeviceInfoById...都需要缓存结果,提供一个通用的辅助函数。

解答:
缓存可根据实际使用场景缓存在不同的地方:

        class CacheHelper {
            constructor() {
                this.cache = new Map();
            }

            getUsersById(userId) {
                if (this.cache.has('users')) {
                    return this.cache.get('users');
                } else {
                    const data = ajax('url');
                    this.cache.set('users', data);
                    return data;
                }
            }

            getShoolInfoById(userId) {
                if (this.cache.has('shoolInfo')) {
                    return this.cache.get('shoolInfo');
                } else {
                    const data = ajax('url');
                    this.cache.set('shoolInfo', data);
                    return data;
                }
            }

            getDeviceInfoById(userId) {
                if (this.cache.has('deviceInfo')) {
                    return this.cache.get('deviceInfo');
                } else {
                    const data = ajax('url');
                    this.cache.set('deviceInfo', data);
                    return data;
                }
            }
        }

        const helper = new CacheHelper();
        console.log(helper.getUsersById());
        console.log(helper.getUsersById());
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容