0
点赞
收藏
分享

微信扫一扫

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

西特张 2021-09-24 阅读 21

假如有一个接口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());
举报

相关推荐

0 条评论