Skip to content

Commit

Permalink
feat(LocalStoragePlus): 新增 increase, decrease
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 25, 2022
1 parent 59c0661 commit d4e9dd9
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/utils/LocalStoragePlus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,32 @@ describe('LocalStoragePlus', () => {
).toBe(null)
})

test('increase 正常', () => {
const countStorage = new LocalStoragePlus<number>({
key: 'increase',
})
expect(countStorage.get()).toBe(null)
countStorage.increase(2)
expect(countStorage.get()).toBe(2)
countStorage.increase(2)
expect(countStorage.get()).toBe(4)
countStorage.increase(-5)
expect(countStorage.get()).toBe(-1)
})

test('decrease 正常', () => {
const countStorage = new LocalStoragePlus<number>({
key: 'decrease',
})
expect(countStorage.get()).toBe(null)
countStorage.decrease(2)
expect(countStorage.get()).toBe(-2)
countStorage.decrease(2)
expect(countStorage.get()).toBe(-4)
countStorage.decrease(-5)
expect(countStorage.get()).toBe(1)
})

test('静态方法正常', () => {
expect(LocalStoragePlus.get<number>('s')).toBe(null)
expect(LocalStoragePlus.has('s')).toBe(false)
Expand Down
58 changes: 58 additions & 0 deletions src/utils/LocalStoragePlus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,44 @@ export class LocalStoragePlus<T extends JsonValue> {
}
}

/**
* 将本地存储的值增加给定值,若本地存储不存在,则初始化为 `0` 后操作。
*
* @param key 键
* @param value 增加值,默认 `1`
* @param options 选项
*/
static increase(
key: string,
value = 1,
options?: LocalStoragePlusSetOptions,
): void {
this.set(
key,
(prevValue: number | null) => Number(prevValue || 0) + value,
options,
)
}

/**
* 将本地存储的值减少给定值,若本地存储不存在,则初始化为 `0` 后操作。
*
* @param key 键
* @param value 减小值,默认 `1`
* @param options 选项
*/
static decrease(
key: string,
value = 1,
options?: LocalStoragePlusSetOptions,
): void {
this.set(
key,
(prevValue: number | null) => Number(prevValue || 0) - value,
options,
)
}

constructor(private options: LocalStoragePlusOptions) {}

/**
Expand Down Expand Up @@ -174,4 +212,24 @@ export class LocalStoragePlus<T extends JsonValue> {
remove(): void {
return LocalStoragePlus.remove(this.options.key)
}

/**
* 自增。
*
* @param value 增加值
* @param options 选项
*/
increase(value = 1, options?: LocalStoragePlusSetOptions): void {
return LocalStoragePlus.increase(this.options.key, value, options)
}

/**
* 自减。
*
* @param value 减少值
* @param options 选项
*/
decrease(value = 1, options?: LocalStoragePlusSetOptions): void {
return LocalStoragePlus.decrease(this.options.key, value, options)
}
}

0 comments on commit d4e9dd9

Please sign in to comment.