index.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /**
  2. * Promise, or maybe not
  3. */
  4. type Awaitable<T> = T | PromiseLike<T>;
  5. /**
  6. * Null or whatever
  7. */
  8. type Nullable<T> = T | null | undefined;
  9. /**
  10. * Array, or not yet
  11. */
  12. type Arrayable<T> = T | Array<T>;
  13. /**
  14. * Function
  15. */
  16. type Fn<T = void> = () => T;
  17. /**
  18. * Constructor
  19. */
  20. type Constructor<T = void> = new (...args: any[]) => T;
  21. /**
  22. * Infers the element type of an array
  23. */
  24. type ElementOf<T> = T extends (infer E)[] ? E : never;
  25. /**
  26. * Defines an intersection type of all union items.
  27. *
  28. * @param U Union of any types that will be intersected.
  29. * @returns U items intersected
  30. * @see https://stackoverflow.com/a/50375286/9259330
  31. */
  32. type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
  33. /**
  34. * Infers the arguments type of a function
  35. */
  36. type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
  37. type MergeInsertions<T> = T extends object ? {
  38. [K in keyof T]: MergeInsertions<T[K]>;
  39. } : T;
  40. type DeepMerge<F, S> = MergeInsertions<{
  41. [K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
  42. }>;
  43. /**
  44. * Convert `Arrayable<T>` to `Array<T>`
  45. *
  46. * @category Array
  47. */
  48. declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
  49. /**
  50. * Convert `Arrayable<T>` to `Array<T>` and flatten it
  51. *
  52. * @category Array
  53. */
  54. declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
  55. /**
  56. * Use rest arguments to merge arrays
  57. *
  58. * @category Array
  59. */
  60. declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
  61. type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
  62. /**
  63. * Divide an array into two parts by a filter function
  64. *
  65. * @category Array
  66. * @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
  67. */
  68. declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
  69. declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
  70. declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
  71. declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
  72. declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
  73. declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
  74. /**
  75. * Unique an Array
  76. *
  77. * @category Array
  78. */
  79. declare function uniq<T>(array: readonly T[]): T[];
  80. /**
  81. * Unique an Array by a custom equality function
  82. *
  83. * @category Array
  84. */
  85. declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
  86. /**
  87. * Get last item
  88. *
  89. * @category Array
  90. */
  91. declare function last(array: readonly []): undefined;
  92. declare function last<T>(array: readonly T[]): T;
  93. /**
  94. * Remove an item from Array
  95. *
  96. * @category Array
  97. */
  98. declare function remove<T>(array: T[], value: T): boolean;
  99. /**
  100. * Get nth item of Array. Negative for backward
  101. *
  102. * @category Array
  103. */
  104. declare function at(array: readonly [], index: number): undefined;
  105. declare function at<T>(array: readonly T[], index: number): T;
  106. /**
  107. * Genrate a range array of numbers. The `stop` is exclusive.
  108. *
  109. * @category Array
  110. */
  111. declare function range(stop: number): number[];
  112. declare function range(start: number, stop: number, step?: number): number[];
  113. /**
  114. * Move element in an Array
  115. *
  116. * @category Array
  117. * @param arr
  118. * @param from
  119. * @param to
  120. */
  121. declare function move<T>(arr: T[], from: number, to: number): T[];
  122. /**
  123. * Clamp a number to the index ranage of an array
  124. *
  125. * @category Array
  126. */
  127. declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
  128. /**
  129. * Get random items from an array
  130. *
  131. * @category Array
  132. */
  133. declare function sample<T>(arr: T[], count: number): T[];
  134. /**
  135. * Shuffle an array. This function mutates the array.
  136. *
  137. * @category Array
  138. */
  139. declare function shuffle<T>(array: T[]): T[];
  140. declare const assert: (condition: boolean, message: string) => asserts condition;
  141. declare const toString: (v: any) => string;
  142. declare const getTypeName: (v: any) => string;
  143. declare const noop: () => void;
  144. /**
  145. * Type guard to filter out null-ish values
  146. *
  147. * @category Guards
  148. * @example array.filter(notNullish)
  149. */
  150. declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
  151. /**
  152. * Type guard to filter out null values
  153. *
  154. * @category Guards
  155. * @example array.filter(noNull)
  156. */
  157. declare function noNull<T>(v: T | null): v is Exclude<T, null>;
  158. /**
  159. * Type guard to filter out null-ish values
  160. *
  161. * @category Guards
  162. * @example array.filter(notUndefined)
  163. */
  164. declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
  165. /**
  166. * Type guard to filter out falsy values
  167. *
  168. * @category Guards
  169. * @example array.filter(isTruthy)
  170. */
  171. declare function isTruthy<T>(v: T): v is NonNullable<T>;
  172. declare const isDef: <T = any>(val?: T | undefined) => val is T;
  173. declare const isBoolean: (val: any) => val is boolean;
  174. declare const isFunction: <T extends Function>(val: any) => val is T;
  175. declare const isNumber: (val: any) => val is number;
  176. declare const isString: (val: unknown) => val is string;
  177. declare const isObject: (val: any) => val is object;
  178. declare const isUndefined: (val: any) => val is undefined;
  179. declare const isNull: (val: any) => val is null;
  180. declare const isRegExp: (val: any) => val is RegExp;
  181. declare const isDate: (val: any) => val is Date;
  182. declare const isWindow: (val: any) => boolean;
  183. declare const isBrowser: boolean;
  184. declare function clamp(n: number, min: number, max: number): number;
  185. declare function sum(...args: number[] | number[][]): number;
  186. /**
  187. * Replace backslash to slash
  188. *
  189. * @category String
  190. */
  191. declare function slash(str: string): string;
  192. /**
  193. * Ensure prefix of a string
  194. *
  195. * @category String
  196. */
  197. declare function ensurePrefix(prefix: string, str: string): string;
  198. /**
  199. * Ensure suffix of a string
  200. *
  201. * @category String
  202. */
  203. declare function ensureSuffix(suffix: string, str: string): string;
  204. /**
  205. * Dead simple template engine, just like Python's `.format()`
  206. *
  207. * @category String
  208. * @example
  209. * ```
  210. * const result = template(
  211. * 'Hello {0}! My name is {1}.',
  212. * 'Inès',
  213. * 'Anthony'
  214. * ) // Hello Inès! My name is Anthony.
  215. * ```
  216. */
  217. declare function template(str: string, ...args: any[]): string;
  218. /**
  219. * Generate a random string
  220. * @category String
  221. */
  222. declare function randomStr(size?: number, dict?: string): string;
  223. /**
  224. * First letter uppercase, other lowercase
  225. * @category string
  226. * @example
  227. * ```
  228. * capitalize('hello') => 'Hello'
  229. * ```
  230. */
  231. declare function capitalize(str: string): string;
  232. declare const timestamp: () => number;
  233. /**
  234. * Call every function in an array
  235. */
  236. declare function batchInvoke(functions: Nullable<Fn>[]): void;
  237. /**
  238. * Call the function
  239. */
  240. declare function invoke(fn: Fn): void;
  241. /**
  242. * Pass the value through the callback, and return the value
  243. *
  244. * @example
  245. * ```
  246. * function createUser(name: string): User {
  247. * return tap(new User, user => {
  248. * user.name = name
  249. * })
  250. * }
  251. * ```
  252. */
  253. declare function tap<T>(value: T, callback: (value: T) => void): T;
  254. /**
  255. * Map key/value pairs for an object, and construct a new one
  256. *
  257. *
  258. * @category Object
  259. *
  260. * Transform:
  261. * @example
  262. * ```
  263. * objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
  264. * // { A: '1', B: '2' }
  265. * ```
  266. *
  267. * Swap key/value:
  268. * @example
  269. * ```
  270. * objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
  271. * // { 1: 'a', 2: 'b' }
  272. * ```
  273. *
  274. * Filter keys:
  275. * @example
  276. * ```
  277. * objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
  278. * // { b: 2 }
  279. * ```
  280. */
  281. declare function objectMap<K extends string, V, NK = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<K, V>;
  282. /**
  283. * Type guard for any key, `k`.
  284. * Marks `k` as a key of `T` if `k` is in `obj`.
  285. *
  286. * @category Object
  287. * @param obj object to query for key `k`
  288. * @param k key to check existence in `obj`
  289. */
  290. declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
  291. /**
  292. * Strict typed `Object.keys`
  293. *
  294. * @category Object
  295. */
  296. declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
  297. /**
  298. * Strict typed `Object.entries`
  299. *
  300. * @category Object
  301. */
  302. declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
  303. /**
  304. * Deep merge :P
  305. *
  306. * @category Object
  307. */
  308. declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
  309. /**
  310. * Create a new subset object by giving keys
  311. *
  312. * @category Object
  313. */
  314. declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
  315. /**
  316. * Clear undefined fields from an object. It mutates the object
  317. *
  318. * @category Object
  319. */
  320. declare function clearUndefined<T extends object>(obj: T): T;
  321. /**
  322. * Determines whether an object has a property with the specified name
  323. *
  324. * @see https://eslint.org/docs/rules/no-prototype-builtins
  325. * @category Object
  326. */
  327. declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
  328. interface SingletonPromiseReturn<T> {
  329. (): Promise<T>;
  330. /**
  331. * Reset current staled promise.
  332. * Await it to have proper shutdown.
  333. */
  334. reset: () => Promise<void>;
  335. }
  336. /**
  337. * Create singleton promise function
  338. *
  339. * @category Promise
  340. */
  341. declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
  342. /**
  343. * Promised `setTimeout`
  344. *
  345. * @category Promise
  346. */
  347. declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
  348. /**
  349. * Create a promise lock
  350. *
  351. * @category Promise
  352. * @example
  353. * ```
  354. * const lock = createPromiseLock()
  355. *
  356. * lock.run(async () => {
  357. * await doSomething()
  358. * })
  359. *
  360. * // in anther context:
  361. * await lock.wait() // it will wait all tasking finished
  362. * ```
  363. */
  364. declare function createPromiseLock(): {
  365. run<T = void>(fn: () => Promise<T>): Promise<T>;
  366. wait(): Promise<void>;
  367. isWaiting(): boolean;
  368. clear(): void;
  369. };
  370. /**
  371. * Promise with `resolve` and `reject` methods of itself
  372. */
  373. interface ControlledPromise<T = void> extends Promise<T> {
  374. resolve(value: T | PromiseLike<T>): void;
  375. reject(reason?: any): void;
  376. }
  377. /**
  378. * Return a Promise with `resolve` and `reject` methods
  379. *
  380. * @category Promise
  381. * @example
  382. * ```
  383. * const promise = createControlledPromise()
  384. *
  385. * await promise
  386. *
  387. * // in anther context:
  388. * promise.resolve(data)
  389. * ```
  390. */
  391. declare function createControlledPromise<T>(): ControlledPromise<T>;
  392. // Type definitions for throttle-debounce 5.0
  393. interface CancelOptions {
  394. upcomingOnly?: boolean;
  395. }
  396. interface Cancel {
  397. cancel: (options?: CancelOptions) => void;
  398. }
  399. interface NoReturn<T extends (...args: any[]) => any> {
  400. (...args: Parameters<T>): void;
  401. }
  402. interface ThrottleOptions {
  403. noTrailing?: boolean;
  404. noLeading?: boolean;
  405. debounceMode?: boolean;
  406. }
  407. interface DebounceOptions {
  408. atBegin?: boolean;
  409. }
  410. type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
  411. /**
  412. * Throttle execution of a function. Especially useful for rate limiting
  413. * execution of handlers on events like resize and scroll.
  414. *
  415. * @param delay
  416. * A zero-or-greater delay in milliseconds. For event callbacks, values around
  417. * 100 or 250 (or even higher) are most useful.
  418. *
  419. * @param callback
  420. * A function to be executed after delay milliseconds. The `this` context and
  421. * all arguments are passed through, as-is, to `callback` when the
  422. * throttled-function is executed.
  423. *
  424. * @param options
  425. * An object to configure options.
  426. *
  427. * @param options.noTrailing
  428. * Optional, defaults to false. If noTrailing is true, callback will only execute
  429. * every `delay` milliseconds while the throttled-function is being called. If
  430. * noTrailing is false or unspecified, callback will be executed one final time
  431. * after the last throttled-function call. (After the throttled-function has not
  432. * been called for `delay` milliseconds, the internal counter is reset)
  433. *
  434. * @param options.noLeading
  435. * Optional, defaults to false. If noLeading is false, the first throttled-function
  436. * call will execute callback immediately. If noLeading is true, the first the
  437. * callback execution will be skipped. It should be noted that callback will never
  438. * executed if both noLeading = true and noTrailing = true.
  439. *
  440. * @param options.debounceMode If `debounceMode` is true (at begin), schedule
  441. * `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
  442. * schedule `callback` to execute after `delay` ms.
  443. *
  444. * @return
  445. * A new, throttled, function.
  446. */
  447. declare function throttle<T extends (...args: any[]) => any>(
  448. delay: number,
  449. callback: T,
  450. options?: ThrottleOptions,
  451. ): throttle<T>;
  452. type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
  453. /**
  454. * Debounce execution of a function. Debouncing, unlike throttling,
  455. * guarantees that a function is only executed a single time, either at the
  456. * very beginning of a series of calls, or at the very end.
  457. *
  458. * @param delay
  459. * A zero-or-greater delay in milliseconds. For event callbacks, values around
  460. * 100 or 250 (or even higher) are most useful.
  461. *
  462. * @param callback
  463. * A function to be executed after delay milliseconds. The `this` context and
  464. * all arguments are passed through, as-is, to `callback` when the
  465. * debounced-function is executed.
  466. *
  467. * @param options
  468. * An object to configure options.
  469. *
  470. * @param options.atBegin
  471. * If atBegin is false or unspecified, callback will only be executed `delay`
  472. * milliseconds after the last debounced-function call. If atBegin is true,
  473. * callback will be executed only at the first debounced-function call. (After
  474. * the throttled-function has not been called for `delay` milliseconds, the
  475. * internal counter is reset).
  476. *
  477. * @return
  478. * A new, debounced function.
  479. */
  480. declare function debounce<T extends (...args: any[]) => any>(
  481. delay: number,
  482. callback: T,
  483. options?: DebounceOptions,
  484. ): debounce<T>;
  485. interface POptions {
  486. /**
  487. * How many promises are resolved at the same time.
  488. */
  489. concurrency?: number | undefined;
  490. }
  491. declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
  492. items: Iterable<T>;
  493. options?: POptions | undefined;
  494. private promises;
  495. get promise(): Promise<Awaited<T>[]>;
  496. constructor(items?: Iterable<T>, options?: POptions | undefined);
  497. add(...args: (T | Promise<T>)[]): void;
  498. map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
  499. filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
  500. forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
  501. reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
  502. clear(): void;
  503. then(fn?: () => PromiseLike<any>): Promise<any>;
  504. catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
  505. finally(fn?: () => void): Promise<Awaited<T>[]>;
  506. }
  507. /**
  508. * Utility for managing multiple promises.
  509. *
  510. * @see https://github.com/antfu/utils/tree/main/docs/p.md
  511. * @category Promise
  512. * @example
  513. * ```
  514. * import { p } from '@antfu/utils'
  515. *
  516. * const items = [1, 2, 3, 4, 5]
  517. *
  518. * await p(items)
  519. * .map(async i => await multiply(i, 3))
  520. * .filter(async i => await isEven(i))
  521. * // [6, 12]
  522. * ```
  523. */
  524. declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
  525. export { ArgumentsType, Arrayable, Awaitable, Constructor, ControlledPromise, DeepMerge, ElementOf, Fn, MergeInsertions, Nullable, PartitionFilter, SingletonPromiseReturn, UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, uniq, uniqueBy };