forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
27 lines (25 loc) · 1.15 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import type { WatchOptions, WatchSource } from 'vue-demi'
import { unref, watch } from 'vue-demi'
export declare type WatchListCallback<V = any, OV = any> = (value: V, oldValue: OV, added: V, removed: OV, onCleanup: (cleanupFn: () => void) => void) => any
export function watchListChanges<T, Immediate extends Readonly<boolean> = false>(source: WatchSource<T[]>, cb: WatchListCallback<T[], Immediate extends true ? T[] | undefined : T[]>, options?: WatchOptions<Immediate>) {
let oldList: T[] = options?.immediate ? [] : [...(source instanceof Function ? source() : unref(source))]
watch(source, (newList, _, onCleanup) => {
const oldListRemains = new Array<boolean>(oldList.length)
const added: T[] = []
for (const obj of newList) {
let found = false
for (let i = 0; i < oldList.length; i++) {
if (!oldListRemains[i] && obj === oldList[i]) {
oldListRemains[i] = true
found = true
break
}
}
if (!found)
added.push(obj)
}
const removed = oldList.filter((_, i) => !oldListRemains[i])
cb(newList, oldList, added, removed, onCleanup)
oldList = [...newList]
}, options)
}