index.d.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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 range of an array
  124. *
  125. * @category Array
  126. */
  127. declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
  128. /**
  129. * Get random item(s) from an array
  130. *
  131. * @param arr
  132. * @param quantity - quantity of random items which will be returned
  133. */
  134. declare function sample<T>(arr: T[], quantity: number): T[];
  135. /**
  136. * Shuffle an array. This function mutates the array.
  137. *
  138. * @category Array
  139. */
  140. declare function shuffle<T>(array: T[]): T[];
  141. declare function assert(condition: boolean, message: string): asserts condition;
  142. declare const toString: (v: any) => string;
  143. declare function getTypeName(v: any): string;
  144. declare function noop(): void;
  145. declare function isDeepEqual(value1: any, value2: any): boolean;
  146. /**
  147. * Type guard to filter out null-ish values
  148. *
  149. * @category Guards
  150. * @example array.filter(notNullish)
  151. */
  152. declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
  153. /**
  154. * Type guard to filter out null values
  155. *
  156. * @category Guards
  157. * @example array.filter(noNull)
  158. */
  159. declare function noNull<T>(v: T | null): v is Exclude<T, null>;
  160. /**
  161. * Type guard to filter out null-ish values
  162. *
  163. * @category Guards
  164. * @example array.filter(notUndefined)
  165. */
  166. declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
  167. /**
  168. * Type guard to filter out falsy values
  169. *
  170. * @category Guards
  171. * @example array.filter(isTruthy)
  172. */
  173. declare function isTruthy<T>(v: T): v is NonNullable<T>;
  174. declare const isDef: <T = any>(val?: T) => val is T;
  175. declare const isBoolean: (val: any) => val is boolean;
  176. declare const isFunction: <T extends Function>(val: any) => val is T;
  177. declare const isNumber: (val: any) => val is number;
  178. declare const isString: (val: unknown) => val is string;
  179. declare const isObject: (val: any) => val is object;
  180. declare const isUndefined: (val: any) => val is undefined;
  181. declare const isNull: (val: any) => val is null;
  182. declare const isRegExp: (val: any) => val is RegExp;
  183. declare const isDate: (val: any) => val is Date;
  184. declare const isWindow: (val: any) => boolean;
  185. declare const isBrowser: boolean;
  186. declare function clamp(n: number, min: number, max: number): number;
  187. declare function sum(...args: number[] | number[][]): number;
  188. /**
  189. * Linearly interpolates between `min` and `max` based on `t`
  190. *
  191. * @category Math
  192. * @param min The minimum value
  193. * @param max The maximum value
  194. * @param t The interpolation value clamped between 0 and 1
  195. * @example
  196. * ```
  197. * const value = lerp(0, 2, 0.5) // value will be 1
  198. * ```
  199. */
  200. declare function lerp(min: number, max: number, t: number): number;
  201. /**
  202. * Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
  203. *
  204. * @category Math
  205. * @example
  206. * ```
  207. * const value = remap(0.5, 0, 1, 200, 400) // value will be 300
  208. * ```
  209. */
  210. declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
  211. /**
  212. * Replace backslash to slash
  213. *
  214. * @category String
  215. */
  216. declare function slash(str: string): string;
  217. /**
  218. * Ensure prefix of a string
  219. *
  220. * @category String
  221. */
  222. declare function ensurePrefix(prefix: string, str: string): string;
  223. /**
  224. * Ensure suffix of a string
  225. *
  226. * @category String
  227. */
  228. declare function ensureSuffix(suffix: string, str: string): string;
  229. /**
  230. * Dead simple template engine, just like Python's `.format()`
  231. * Support passing variables as either in index based or object/name based approach
  232. * While using object/name based approach, you can pass a fallback value as the third argument
  233. *
  234. * @category String
  235. * @example
  236. * ```
  237. * const result = template(
  238. * 'Hello {0}! My name is {1}.',
  239. * 'Inès',
  240. * 'Anthony'
  241. * ) // Hello Inès! My name is Anthony.
  242. * ```
  243. *
  244. * ```
  245. * const result = namedTemplate(
  246. * '{greet}! My name is {name}.',
  247. * { greet: 'Hello', name: 'Anthony' }
  248. * ) // Hello! My name is Anthony.
  249. * ```
  250. *
  251. * const result = namedTemplate(
  252. * '{greet}! My name is {name}.',
  253. * { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
  254. * 'placeholder'
  255. * ) // Hello! My name is placeholder.
  256. * ```
  257. */
  258. declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
  259. declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
  260. /**
  261. * Generate a random string
  262. * @category String
  263. */
  264. declare function randomStr(size?: number, dict?: string): string;
  265. /**
  266. * First letter uppercase, other lowercase
  267. * @category string
  268. * @example
  269. * ```
  270. * capitalize('hello') => 'Hello'
  271. * ```
  272. */
  273. declare function capitalize(str: string): string;
  274. /**
  275. * Remove common leading whitespace from a template string.
  276. * Will also remove empty lines at the beginning and end.
  277. * @category string
  278. * @example
  279. * ```ts
  280. * const str = unindent`
  281. * if (a) {
  282. * b()
  283. * }
  284. * `
  285. */
  286. declare function unindent(str: TemplateStringsArray | string): string;
  287. declare const timestamp: () => number;
  288. /**
  289. * Call every function in an array
  290. */
  291. declare function batchInvoke(functions: Nullable<Fn>[]): void;
  292. /**
  293. * Call the function
  294. */
  295. declare function invoke(fn: Fn): void;
  296. /**
  297. * Pass the value through the callback, and return the value
  298. *
  299. * @example
  300. * ```
  301. * function createUser(name: string): User {
  302. * return tap(new User, user => {
  303. * user.name = name
  304. * })
  305. * }
  306. * ```
  307. */
  308. declare function tap<T>(value: T, callback: (value: T) => void): T;
  309. /**
  310. * Map key/value pairs for an object, and construct a new one
  311. *
  312. *
  313. * @category Object
  314. *
  315. * Transform:
  316. * @example
  317. * ```
  318. * objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
  319. * // { A: '1', B: '2' }
  320. * ```
  321. *
  322. * Swap key/value:
  323. * @example
  324. * ```
  325. * objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
  326. * // { 1: 'a', 2: 'b' }
  327. * ```
  328. *
  329. * Filter keys:
  330. * @example
  331. * ```
  332. * objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
  333. * // { b: 2 }
  334. * ```
  335. */
  336. declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
  337. /**
  338. * Type guard for any key, `k`.
  339. * Marks `k` as a key of `T` if `k` is in `obj`.
  340. *
  341. * @category Object
  342. * @param obj object to query for key `k`
  343. * @param k key to check existence in `obj`
  344. */
  345. declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
  346. /**
  347. * Strict typed `Object.keys`
  348. *
  349. * @category Object
  350. */
  351. 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}`)[];
  352. /**
  353. * Strict typed `Object.entries`
  354. *
  355. * @category Object
  356. */
  357. declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
  358. /**
  359. * Deep merge
  360. *
  361. * The first argument is the target object, the rest are the sources.
  362. * The target object will be mutated and returned.
  363. *
  364. * @category Object
  365. */
  366. declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
  367. /**
  368. * Deep merge
  369. *
  370. * Differs from `deepMerge` in that it merges arrays instead of overriding them.
  371. *
  372. * The first argument is the target object, the rest are the sources.
  373. * The target object will be mutated and returned.
  374. *
  375. * @category Object
  376. */
  377. declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
  378. /**
  379. * Create a new subset object by giving keys
  380. *
  381. * @category Object
  382. */
  383. declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
  384. /**
  385. * Clear undefined fields from an object. It mutates the object
  386. *
  387. * @category Object
  388. */
  389. declare function clearUndefined<T extends object>(obj: T): T;
  390. /**
  391. * Determines whether an object has a property with the specified name
  392. *
  393. * @see https://eslint.org/docs/rules/no-prototype-builtins
  394. * @category Object
  395. */
  396. declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
  397. interface SingletonPromiseReturn<T> {
  398. (): Promise<T>;
  399. /**
  400. * Reset current staled promise.
  401. * Await it to have proper shutdown.
  402. */
  403. reset: () => Promise<void>;
  404. }
  405. /**
  406. * Create singleton promise function
  407. *
  408. * @category Promise
  409. */
  410. declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
  411. /**
  412. * Promised `setTimeout`
  413. *
  414. * @category Promise
  415. */
  416. declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
  417. /**
  418. * Create a promise lock
  419. *
  420. * @category Promise
  421. * @example
  422. * ```
  423. * const lock = createPromiseLock()
  424. *
  425. * lock.run(async () => {
  426. * await doSomething()
  427. * })
  428. *
  429. * // in anther context:
  430. * await lock.wait() // it will wait all tasking finished
  431. * ```
  432. */
  433. declare function createPromiseLock(): {
  434. run<T = void>(fn: () => Promise<T>): Promise<T>;
  435. wait(): Promise<void>;
  436. isWaiting(): boolean;
  437. clear(): void;
  438. };
  439. /**
  440. * Promise with `resolve` and `reject` methods of itself
  441. */
  442. interface ControlledPromise<T = void> extends Promise<T> {
  443. resolve: (value: T | PromiseLike<T>) => void;
  444. reject: (reason?: any) => void;
  445. }
  446. /**
  447. * Return a Promise with `resolve` and `reject` methods
  448. *
  449. * @category Promise
  450. * @example
  451. * ```
  452. * const promise = createControlledPromise()
  453. *
  454. * await promise
  455. *
  456. * // in anther context:
  457. * promise.resolve(data)
  458. * ```
  459. */
  460. declare function createControlledPromise<T>(): ControlledPromise<T>;
  461. interface CancelOptions {
  462. upcomingOnly?: boolean;
  463. }
  464. interface Cancel {
  465. cancel: (options?: CancelOptions) => void;
  466. }
  467. interface NoReturn<T extends (...args: any[]) => any> {
  468. (...args: Parameters<T>): void;
  469. }
  470. interface ThrottleOptions {
  471. noTrailing?: boolean;
  472. noLeading?: boolean;
  473. debounceMode?: boolean;
  474. }
  475. interface DebounceOptions {
  476. atBegin?: boolean;
  477. }
  478. type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
  479. /**
  480. * Throttle execution of a function. Especially useful for rate limiting
  481. * execution of handlers on events like resize and scroll.
  482. *
  483. * @param delay
  484. * A zero-or-greater delay in milliseconds. For event callbacks, values around
  485. * 100 or 250 (or even higher) are most useful.
  486. *
  487. * @param callback
  488. * A function to be executed after delay milliseconds. The `this` context and
  489. * all arguments are passed through, as-is, to `callback` when the
  490. * throttled-function is executed.
  491. *
  492. * @param options
  493. * An object to configure options.
  494. *
  495. * @param options.noTrailing
  496. * Optional, defaults to false. If noTrailing is true, callback will only execute
  497. * every `delay` milliseconds while the throttled-function is being called. If
  498. * noTrailing is false or unspecified, callback will be executed one final time
  499. * after the last throttled-function call. (After the throttled-function has not
  500. * been called for `delay` milliseconds, the internal counter is reset)
  501. *
  502. * @param options.noLeading
  503. * Optional, defaults to false. If noLeading is false, the first throttled-function
  504. * call will execute callback immediately. If noLeading is true, the first the
  505. * callback execution will be skipped. It should be noted that callback will never
  506. * executed if both noLeading = true and noTrailing = true.
  507. *
  508. * @param options.debounceMode If `debounceMode` is true (at begin), schedule
  509. * `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
  510. * schedule `callback` to execute after `delay` ms.
  511. *
  512. * @return
  513. * A new, throttled, function.
  514. */
  515. declare function throttle<T extends (...args: any[]) => any>(
  516. delay: number,
  517. callback: T,
  518. options?: ThrottleOptions,
  519. ): throttle<T>;
  520. type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
  521. /**
  522. * Debounce execution of a function. Debouncing, unlike throttling,
  523. * guarantees that a function is only executed a single time, either at the
  524. * very beginning of a series of calls, or at the very end.
  525. *
  526. * @param delay
  527. * A zero-or-greater delay in milliseconds. For event callbacks, values around
  528. * 100 or 250 (or even higher) are most useful.
  529. *
  530. * @param callback
  531. * A function to be executed after delay milliseconds. The `this` context and
  532. * all arguments are passed through, as-is, to `callback` when the
  533. * debounced-function is executed.
  534. *
  535. * @param options
  536. * An object to configure options.
  537. *
  538. * @param options.atBegin
  539. * If atBegin is false or unspecified, callback will only be executed `delay`
  540. * milliseconds after the last debounced-function call. If atBegin is true,
  541. * callback will be executed only at the first debounced-function call. (After
  542. * the throttled-function has not been called for `delay` milliseconds, the
  543. * internal counter is reset).
  544. *
  545. * @return
  546. * A new, debounced function.
  547. */
  548. declare function debounce<T extends (...args: any[]) => any>(
  549. delay: number,
  550. callback: T,
  551. options?: DebounceOptions,
  552. ): debounce<T>;
  553. interface POptions {
  554. /**
  555. * How many promises are resolved at the same time.
  556. */
  557. concurrency?: number | undefined;
  558. }
  559. declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
  560. items: Iterable<T>;
  561. options?: POptions | undefined;
  562. private promises;
  563. get promise(): Promise<Awaited<T>[]>;
  564. constructor(items?: Iterable<T>, options?: POptions | undefined);
  565. add(...args: (T | Promise<T>)[]): void;
  566. map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
  567. filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
  568. forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
  569. reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
  570. clear(): void;
  571. then(fn?: () => PromiseLike<any>): Promise<any>;
  572. catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
  573. finally(fn?: () => void): Promise<Awaited<T>[]>;
  574. }
  575. /**
  576. * Utility for managing multiple promises.
  577. *
  578. * @see https://github.com/antfu/utils/tree/main/docs/p.md
  579. * @category Promise
  580. * @example
  581. * ```
  582. * import { p } from '@antfu/utils'
  583. *
  584. * const items = [1, 2, 3, 4, 5]
  585. *
  586. * await p(items)
  587. * .map(async i => await multiply(i, 3))
  588. * .filter(async i => await isEven(i))
  589. * // [6, 12]
  590. * ```
  591. */
  592. declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
  593. export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };