| 139 | * |
| 140 | */ |
| 141 | export function createOrUpdate<T, S extends keyof T, P = T[S]>( |
| 142 | obj: T, |
| 143 | fnAttr: S, |
| 144 | rate: number, |
| 145 | throttleType: ThrottleType |
| 146 | ): P extends ThrottleFunction ? P & ThrottleController : never { |
| 147 | let fn = obj[fnAttr]; |
| 148 | |
| 149 | if (!fn) { |
| 150 | return; |
| 151 | } |
| 152 | |
| 153 | const originFn = (fn as any)[ORIGIN_METHOD] || fn; |
| 154 | const lastThrottleType = (fn as any)[THROTTLE_TYPE]; |
| 155 | const lastRate = (fn as any)[RATE]; |
| 156 | |
| 157 | if (lastRate !== rate || lastThrottleType !== throttleType) { |
| 158 | if (rate == null || !throttleType) { |
| 159 | return (obj[fnAttr] = originFn); |
| 160 | } |
| 161 | |
| 162 | fn = obj[fnAttr] = throttle( |
| 163 | originFn, rate, throttleType === 'debounce' |
| 164 | ); |
| 165 | (fn as any)[ORIGIN_METHOD] = originFn; |
| 166 | (fn as any)[THROTTLE_TYPE] = throttleType; |
| 167 | (fn as any)[RATE] = rate; |
| 168 | } |
| 169 | |
| 170 | return fn as ReturnType<typeof createOrUpdate>; |
| 171 | } |
| 172 | |
| 173 | /** |
| 174 | * Clear throttle. Example see throttle.createOrUpdate. |