index.d.ts 16 KB

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