学习ts(十一)本地存储与发布订阅模式

localStorage实现过期时间

目录

准备

安装

js 复制代码
npm i rollup typescript rollup-plugin-typescript2
js 复制代码
// tsconfig.json
 "module": "ESNext",
 "moduleResolution": "node",    
 "strict": false,     
js 复制代码
// rollup.config.js
import ts from 'rollup-plugin-typescript2'
import path from 'path'
import { fileURLToPath } from 'url'
const mateUrl = fileURLToPath(import.meta.url)
const dirName = path.dirname(mateUrl)
export default {
    input: "./src/index.ts",
    output: {
        file: path.resolve(dirName, './dist/index.js')
    },
    plugins:[
        ts()
    ]
}

开发

js 复制代码
// enum/index.ts
export enum Dictionaries {
    permanent = 'permanent',  //永久
    expire = '__expire__'
}
js 复制代码
// type/index.ts
import { Dictionaries } from "../enum"

export type Expire = Dictionaries.permanent | number //传递永久或者时间戳
export type Key = string

export interface StorageCls {
    get: <T>(key: Key) => void
    set: <T>(key: Key, value: T, expire: Expire) => void
    remove: (key: Key) => void
    clear: () => void
}
export interface Data<T> {
    value: T,
    [Dictionaries.expire]: Expire
}
export interface Result<T> {
    message: string,
    value: T | null
}
js 复制代码
// index.ts
import { Key, StorageCls, Expire, Data, Result } from "./type";
import { Dictionaries } from "./enum"
export class Storage implements StorageCls {
    get<T>(key: Key):Result<T | null> {
        const value = localStorage.getItem(key)

        if (value) {
            const data = JSON.parse(value)
            const now = new Date().getTime()
            // 过期
            if (typeof data[Dictionaries.expire] == 'number' && data[Dictionaries.expire] < now) {
                this.remove(key)
                return {
                    message: `您的 ${key}已过期`,
                    value: null
                }
            } else {
                return {
                    message: `成功`,
                    value: data.value
                }
            }
        } else {
            return {
                message: '值无效',
                value: null
            }
        }
    }
    set<T>(key: Key, value: T, expire: Expire): void {
        const data: Data<T> = {
            value,
            [Dictionaries.expire]: expire
        }
        localStorage.setItem(key, JSON.stringify(data))
    }

    remove(key: Key) {
        localStorage.removeItem(key)
    }
    clear() {
        localStorage.clear()
    };

}

测试

js 复制代码
<script type="module">
        import {Storage} from './dist/index.js'
        let s = new Storage()
        s.set('test','orange',new Date().getTime()+3000)
        // setInterval(()=>{
        //     console.log(s.get('test'))
        // },1000)
    </script>

发布订阅模式

js 复制代码
type Key = string
interface EventInit {
    on: (key: Key, fn: Function) => void
    emit: (key: Key, ...args: Array<any>) => void
    off: (key: Key, fn: Function) => void
    once: (key: Key, fn: Function) => void
}

interface List {
    [key: string]: Array<Function>
}

class Dispatch implements EventInit {
    list: List
    constructor() {
        this.list = {}
    }
    on(key: Key, fn: Function) {
        const callback = this.list[key] || []
        callback.push(fn)
        this.list[key] = callback
        // console.log(this.list)
    }
    emit(key: Key, ...args: Array<any>) {
        if (this.list[key] && this.list[key].length > 0) {
            this.list[key].forEach(item => {
                item.apply(this, args)
            })
        } else {
            console.error('名称错误')
        }

    }
    off(key: Key, fn: Function) {
        if (this.list[key] && this.list[key].length > 0) {
            let index = this.list[key].findIndex(i => i === fn)
            if (index > -1) {
                this.list[key].splice(index, 1)
            } else {
                console.error(`方法不存在`)
            }
        } else {
            console.error(`名称错误${key}`)
        }
    }
    once(key: Key, fn: Function) {
        let tempFn = (...args: Array<any>) => {
            fn.apply(this, args)
            this.off(key, tempFn)
        }
        this.on(key, tempFn)
    }
}
const o = new Dispatch()
o.on('post', (...args) => {
    console.log(args)
})
o.on('post', (...args) => {
    console.log(args)
})
o.on('put', (...args) => {
    console.log(args)
})
let fn = (...args) => {
    console.log(args)
}
// o.on('get', fn)
o.once('get', fn)
o.emit('get', fn)
o.emit('get', fn)
// o.emit('put', 1, '373', { name: 'hello' })
// o.off('get', fn)
// o.emit('get', 2, '373', { name: 'hello' })
相关推荐
laplace01232 分钟前
Claude Code 逆向工程报告 笔记(学习记录)
数据库·人工智能·笔记·学习·agent·rag
lingggggaaaa6 分钟前
安全工具篇&Go魔改二开&Fscan扫描&FRP代理&特征消除&新增扩展&打乱HASH
学习·安全·web安全·网络安全·golang·哈希算法
夏幻灵29 分钟前
过来人的经验-前端学习路线
前端
CappuccinoRose1 小时前
React框架学习文档(七)
开发语言·前端·javascript·react.js·前端框架·reactjs·react router
Daydream.V1 小时前
网页学习——HTML
学习
FFF-X1 小时前
前端字符串模糊匹配实现:精准匹配 + Levenshtein 编辑距离兜底
前端
张永清-老清1 小时前
每周读书与学习->JMeter性能测试脚本编写实战(四)-利用JMeter对MySQL数据库查询进行性能测试
学习·jmeter·性能调优·jmeter性能测试·性能分析·每周读书与学习
Hi_kenyon1 小时前
Ref和Reactive都是什么时候使用?
前端·javascript·vue.js
InterestOriented1 小时前
中老年线上学习发展:兴趣岛“内容+服务+空间”融合赋能下的体验升级
人工智能·学习
宇钶宇夕1 小时前
CoDeSys入门实战一起学习(二十八):(ST)三台电机顺起逆停程序详解
运维·学习·自动化·软件工程