@oscarpalmer/atoms 0.146.0 → 0.148.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/array/from.js +18 -0
  2. package/dist/array/misc.js +2 -2
  3. package/dist/atoms.full.js +109 -39
  4. package/dist/function/work.js +29 -10
  5. package/dist/index.js +4 -3
  6. package/dist/internal/result.js +25 -0
  7. package/dist/random.js +1 -1
  8. package/dist/{result.js → result/index.js} +6 -25
  9. package/dist/result/models.js +0 -0
  10. package/dist/result/work/flow.js +25 -0
  11. package/dist/result/work/pipe.js +21 -0
  12. package/package.json +3 -3
  13. package/src/array/from.ts +89 -0
  14. package/src/array/misc.ts +1 -1
  15. package/src/array/toggle.ts +2 -2
  16. package/src/array/update.ts +2 -2
  17. package/src/function/work.ts +316 -254
  18. package/src/index.ts +1 -1
  19. package/src/internal/result.ts +80 -0
  20. package/src/math.ts +1 -1
  21. package/src/promise.ts +3 -3
  22. package/src/random.ts +1 -1
  23. package/src/{result.ts → result/index.ts} +14 -113
  24. package/src/result/models.ts +57 -0
  25. package/src/result/work/flow.ts +433 -0
  26. package/src/result/work/pipe.ts +791 -0
  27. package/types/array/from.d.ts +41 -0
  28. package/types/array/misc.d.ts +1 -1
  29. package/types/array/toggle.d.ts +2 -2
  30. package/types/array/update.d.ts +2 -2
  31. package/types/function/work.d.ts +51 -50
  32. package/types/index.d.ts +1 -1
  33. package/types/internal/result.d.ts +37 -0
  34. package/types/math.d.ts +1 -1
  35. package/types/promise.d.ts +3 -3
  36. package/types/random.d.ts +1 -1
  37. package/types/{result.d.ts → result/index.d.ts} +8 -66
  38. package/types/result/models.d.ts +38 -0
  39. package/types/result/work/flow.d.ts +134 -0
  40. package/types/result/work/pipe.d.ts +271 -0
  41. package/dist/array/range.js +0 -6
  42. package/src/array/range.ts +0 -35
  43. package/types/array/range.d.ts +0 -20
@@ -0,0 +1,18 @@
1
+ function range(first, second, third) {
2
+ const start = typeof second === "number" ? first : 0;
3
+ const end = typeof second === "number" ? second : first;
4
+ const step = typeof third === "number" ? third : 1;
5
+ const values = [];
6
+ if (step === 0) return values;
7
+ if (step > 0) for (let i = start; i < end; i += step) values.push(i);
8
+ else for (let i = start; i > end; i += step) values.push(i);
9
+ return values;
10
+ }
11
+ function times(length, value) {
12
+ if (typeof length !== "number" || length <= 0) return [];
13
+ const isFunction = typeof value === "function";
14
+ const values = [];
15
+ for (let index = 0; index < length; index += 1) values.push(isFunction ? value(index) : value ?? index);
16
+ return values;
17
+ }
18
+ export { range, times };
@@ -2,6 +2,7 @@ import { exists } from "./exists.js";
2
2
  import { filter } from "./filter.js";
3
3
  import { find } from "./find.js";
4
4
  import { flatten } from "./flatten.js";
5
+ import { range, times } from "./from.js";
5
6
  import { getArray } from "./get.js";
6
7
  import { indexOf } from "./index-of.js";
7
8
  import { chunk } from "../internal/array/chunk.js";
@@ -10,11 +11,10 @@ import { compact } from "../internal/array/compact.js";
10
11
  import { shuffle } from "../internal/array/shuffle.js";
11
12
  import { partition } from "./partition.js";
12
13
  import { push } from "./push.js";
13
- import { range } from "./range.js";
14
14
  import { select } from "./select.js";
15
15
  import { sort } from "./sort.js";
16
16
  import { splice } from "./splice.js";
17
17
  import { toSet } from "./to-set.js";
18
18
  import { toggle } from "./toggle.js";
19
19
  import { update } from "./update.js";
20
- export { chunk, compact, exists, filter, find, flatten, getArray, indexOf, insert, partition, push, range, select, shuffle, sort, splice, toSet, toggle, update };
20
+ export { chunk, compact, exists, filter, find, flatten, getArray, indexOf, insert, partition, push, range, select, shuffle, sort, splice, times, toSet, toggle, update };
@@ -284,6 +284,23 @@ function find(array, ...parameters) {
284
284
  function flatten(array) {
285
285
  return Array.isArray(array) ? array.flat(Number.POSITIVE_INFINITY) : [];
286
286
  }
287
+ function range(first, second, third) {
288
+ const start = typeof second === "number" ? first : 0;
289
+ const end = typeof second === "number" ? second : first;
290
+ const step = typeof third === "number" ? third : 1;
291
+ const values = [];
292
+ if (step === 0) return values;
293
+ if (step > 0) for (let i = start; i < end; i += step) values.push(i);
294
+ else for (let i = start; i > end; i += step) values.push(i);
295
+ return values;
296
+ }
297
+ function times(length, value) {
298
+ if (typeof length !== "number" || length <= 0) return [];
299
+ const isFunction = typeof value === "function";
300
+ const values = [];
301
+ for (let index = 0; index < length; index += 1) values.push(isFunction ? value(index) : value ?? index);
302
+ return values;
303
+ }
287
304
  function getArray(value, indiced) {
288
305
  if (Array.isArray(value)) return value;
289
306
  if (value instanceof Map || value instanceof Set) return [...value.values()];
@@ -338,11 +355,6 @@ function partition(array, ...parameters) {
338
355
  function push(array, pushed) {
339
356
  return insertValues("push", array, pushed, array.length, 0);
340
357
  }
341
- function range(length, value) {
342
- if (typeof length !== "number" || length <= 0) return [];
343
- const isFunction = typeof value === "function";
344
- return Array.from({ length }, (_, index) => isFunction ? value(index) : value ?? index);
345
- }
346
358
  function select(array, ...parameters) {
347
359
  return findValues("all", array, parameters, parameters.pop()).matched;
348
360
  }
@@ -942,6 +954,29 @@ const DEFAULT_CACHE_SIZE = 1024;
942
954
  function throttle(callback, time) {
943
955
  return getLimiter(callback, true, time);
944
956
  }
957
+ function _isResult(value, okValue) {
958
+ if (!isPlainObject(value)) return false;
959
+ return value.ok === okValue && (okValue ? "value" : "error") in value;
960
+ }
961
+ function isError(value, extended) {
962
+ return _isResult(value, false) && (extended === true ? value.original instanceof Error : true);
963
+ }
964
+ /**
965
+ * Is the result ok?
966
+ * @param result Result to check
967
+ * @returns `true` if the result is ok, `false` otherwise
968
+ */
969
+ function isOk(value) {
970
+ return _isResult(value, true);
971
+ }
972
+ /**
973
+ * Is the value a result?
974
+ * @param value Value to check
975
+ * @returns `true` if the value is a result, `false` otherwise
976
+ */
977
+ function isResult(value) {
978
+ return _isResult(value, true) || _isResult(value, false);
979
+ }
945
980
  function assert(condition, message, error) {
946
981
  if (!condition()) throw new (error ?? Error)(message);
947
982
  }
@@ -962,11 +997,17 @@ assert.is = (condition, message, error) => {
962
997
  };
963
998
  function asyncFlow(...fns) {
964
999
  assertFlowFunctions(fns);
965
- return (...args) => asyncWork(args, fns, true);
1000
+ return (...args) => asyncWork(args.map((value) => {
1001
+ if (isError(value)) throw value.error;
1002
+ return isOk(value) ? value.value : value;
1003
+ }), fns, true);
966
1004
  }
967
1005
  function flow(...fns) {
968
1006
  assertFlowFunctions(fns);
969
- return (...args) => work(args, fns, true);
1007
+ return (...args) => work(args.map((value) => {
1008
+ if (isError(value)) throw value.error;
1009
+ return isOk(value) ? value.value : value;
1010
+ }), fns, true);
970
1011
  }
971
1012
  flow.async = asyncFlow;
972
1013
  async function asyncPipe(value, ...pipes) {
@@ -980,26 +1021,38 @@ function pipe(value, ...pipes) {
980
1021
  pipe.async = asyncPipe;
981
1022
  async function asyncWork(initial, functions, flow) {
982
1023
  const { length } = functions;
983
- let transformed = initial;
1024
+ let transformed = unwrapValue(initial);
984
1025
  for (let index = 0; index < length; index += 1) {
985
1026
  const fn = functions[index];
986
- transformed = flow && index === 0 && Array.isArray(initial) ? await fn(...initial) : await fn(transformed);
1027
+ transformed = unwrapValue(flow && index === 0 && Array.isArray(initial) ? await fn(...initial) : await fn(transformed));
987
1028
  }
988
1029
  return transformed;
989
1030
  }
1031
+ function unwrapValue(value, flow, nested) {
1032
+ if (typeof value === "function") {
1033
+ if (nested != null) throw new TypeError(MESSAGE_NESTING);
1034
+ return unwrapValue(value(), flow, true);
1035
+ }
1036
+ if (flow != null && value instanceof Promise) throw new TypeError(flow ? MESSAGE_FLOW_PROMISE : MESSAGE_PIPE_PROMISE);
1037
+ if (isError(value)) throw value.error;
1038
+ return isOk(value) ? value.value : value;
1039
+ }
990
1040
  function work(initial, functions, flow) {
991
1041
  const { length } = functions;
992
- let transformed = initial;
1042
+ let transformed = unwrapValue(initial, flow);
993
1043
  for (let index = 0; index < length; index += 1) {
994
1044
  const fn = functions[index];
995
- transformed = flow && index === 0 && Array.isArray(initial) ? fn(...initial) : fn(transformed);
1045
+ transformed = unwrapValue(flow && index === 0 && Array.isArray(initial) ? fn(...initial) : fn(transformed), flow);
996
1046
  }
997
1047
  return transformed;
998
1048
  }
999
- const MESSAGE_FLOW = "Flow expected to receive an array of functions";
1000
- const MESSAGE_PIPE = "Pipe expected to receive an array of functions";
1001
- const assertFlowFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_FLOW, TypeError);
1002
- const assertPipeFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_PIPE, TypeError);
1049
+ const MESSAGE_FLOW_ARRAY = "Flow expected to receive an array of functions";
1050
+ const MESSAGE_FLOW_PROMISE = "Synchronous Flow received a promise. Use `flow.async` instead.";
1051
+ const MESSAGE_NESTING = "Return values are too deeply nested.";
1052
+ const MESSAGE_PIPE_ARRAY = "Pipe expected to receive an array of functions";
1053
+ const MESSAGE_PIPE_PROMISE = "Synchronous Pipe received a promise. Use `pipe.async` instead.";
1054
+ const assertFlowFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_FLOW_ARRAY, TypeError);
1055
+ const assertPipeFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_PIPE_ARRAY, TypeError);
1003
1056
  /**
1004
1057
  * A function that does nothing, which can be useful, I guess…
1005
1058
  */
@@ -3431,7 +3484,7 @@ const MESSAGE_MAXIMUM = "Queue has reached its maximum size";
3431
3484
  const MESSAGE_REMOVE = "Item removed from queue";
3432
3485
  /**
3433
3486
  * Get a random boolean
3434
- * @return Random boolean
3487
+ * @returns Random boolean
3435
3488
  */
3436
3489
  function getRandomBoolean() {
3437
3490
  return Math.random() > BOOLEAN_MODIFIER;
@@ -3483,10 +3536,44 @@ const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
3483
3536
  const BOOLEAN_MODIFIER = .5;
3484
3537
  const HEX_CHARACTERS = "0123456789ABCDEF";
3485
3538
  const HEX_MAXIMUM = 15;
3486
- function _isResult(value, okValue) {
3487
- if (!isPlainObject(value)) return false;
3488
- return value.ok === okValue && (okValue ? "value" : "error") in value;
3539
+ function attemptAsyncFlow(...fns) {
3540
+ let Flow;
3541
+ return (...args) => attempt.async(() => {
3542
+ Flow ??= flow.async(...fns);
3543
+ return Flow(...args.map((value) => {
3544
+ if (isError(value)) throw value.error;
3545
+ return isOk(value) ? value.value : value;
3546
+ }));
3547
+ });
3548
+ }
3549
+ function attemptFlow(...fns) {
3550
+ let Flow;
3551
+ return (...args) => attempt(() => {
3552
+ Flow ??= flow(...fns);
3553
+ return Flow(...args.map((value) => {
3554
+ if (isError(value)) throw value.error;
3555
+ return isOk(value) ? value.value : value;
3556
+ }));
3557
+ });
3558
+ }
3559
+ attemptFlow.async = attemptAsyncFlow;
3560
+ async function attemptAsyncPipe(initial, first, ...seconds) {
3561
+ return attempt.async(() => {
3562
+ if (isError(initial)) throw initial.error;
3563
+ const value = typeof initial === "function" ? initial() : isOk(initial) ? initial.value : initial;
3564
+ if (first == null) return value;
3565
+ return pipe.async(value, ...[first, ...seconds]);
3566
+ });
3567
+ }
3568
+ function attemptPipe(initial, first, ...seconds) {
3569
+ return attempt(() => {
3570
+ if (isError(initial)) throw initial.error;
3571
+ const value = typeof initial === "function" ? initial() : isOk(initial) ? initial.value : initial;
3572
+ if (first == null) return value;
3573
+ return pipe(value, ...[first, ...seconds]);
3574
+ });
3489
3575
  }
3576
+ attemptPipe.async = attemptAsyncPipe;
3490
3577
  async function asyncAttempt(value, err) {
3491
3578
  try {
3492
3579
  let result = typeof value === "function" ? value() : await value;
@@ -3504,6 +3591,8 @@ function attempt(callback, err) {
3504
3591
  }
3505
3592
  }
3506
3593
  attempt.async = asyncAttempt;
3594
+ attempt.flow = attemptFlow;
3595
+ attempt.pipe = attemptPipe;
3507
3596
  attempt.promise = attemptPromise;
3508
3597
  function error(value, original) {
3509
3598
  return getError(value, original);
@@ -3516,25 +3605,6 @@ function getError(value, original) {
3516
3605
  if (original instanceof Error) errorResult.original = original;
3517
3606
  return errorResult;
3518
3607
  }
3519
- function isError(value, extended) {
3520
- return _isResult(value, false) && (extended === true ? value.original instanceof Error : true);
3521
- }
3522
- /**
3523
- * Is the result ok?
3524
- * @param result Result to check
3525
- * @returns `true` if the result is ok, `false` otherwise
3526
- */
3527
- function isOk(value) {
3528
- return _isResult(value, true);
3529
- }
3530
- /**
3531
- * Is the value a result?
3532
- * @param value Value to check
3533
- * @returns `true` if the value is a result, `false` otherwise
3534
- */
3535
- function isResult(value) {
3536
- return _isResult(value, true) || _isResult(value, false);
3537
- }
3538
3608
  /**
3539
3609
  * Creates an ok result
3540
3610
  * @param value Value
@@ -3601,4 +3671,4 @@ var SizedSet = class extends Set {
3601
3671
  }
3602
3672
  }
3603
3673
  };
3604
- export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, fromQuery, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
3674
+ export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, fromQuery, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, times, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
@@ -1,11 +1,18 @@
1
1
  import { assert } from "./assert.js";
2
+ import { isError, isOk } from "../internal/result.js";
2
3
  function asyncFlow(...fns) {
3
4
  assertFlowFunctions(fns);
4
- return (...args) => asyncWork(args, fns, true);
5
+ return (...args) => asyncWork(args.map((value) => {
6
+ if (isError(value)) throw value.error;
7
+ return isOk(value) ? value.value : value;
8
+ }), fns, true);
5
9
  }
6
10
  function flow(...fns) {
7
11
  assertFlowFunctions(fns);
8
- return (...args) => work(args, fns, true);
12
+ return (...args) => work(args.map((value) => {
13
+ if (isError(value)) throw value.error;
14
+ return isOk(value) ? value.value : value;
15
+ }), fns, true);
9
16
  }
10
17
  flow.async = asyncFlow;
11
18
  async function asyncPipe(value, ...pipes) {
@@ -19,24 +26,36 @@ function pipe(value, ...pipes) {
19
26
  pipe.async = asyncPipe;
20
27
  async function asyncWork(initial, functions, flow) {
21
28
  const { length } = functions;
22
- let transformed = initial;
29
+ let transformed = unwrapValue(initial);
23
30
  for (let index = 0; index < length; index += 1) {
24
31
  const fn = functions[index];
25
- transformed = flow && index === 0 && Array.isArray(initial) ? await fn(...initial) : await fn(transformed);
32
+ transformed = unwrapValue(flow && index === 0 && Array.isArray(initial) ? await fn(...initial) : await fn(transformed));
26
33
  }
27
34
  return transformed;
28
35
  }
36
+ function unwrapValue(value, flow, nested) {
37
+ if (typeof value === "function") {
38
+ if (nested != null) throw new TypeError(MESSAGE_NESTING);
39
+ return unwrapValue(value(), flow, true);
40
+ }
41
+ if (flow != null && value instanceof Promise) throw new TypeError(flow ? MESSAGE_FLOW_PROMISE : MESSAGE_PIPE_PROMISE);
42
+ if (isError(value)) throw value.error;
43
+ return isOk(value) ? value.value : value;
44
+ }
29
45
  function work(initial, functions, flow) {
30
46
  const { length } = functions;
31
- let transformed = initial;
47
+ let transformed = unwrapValue(initial, flow);
32
48
  for (let index = 0; index < length; index += 1) {
33
49
  const fn = functions[index];
34
- transformed = flow && index === 0 && Array.isArray(initial) ? fn(...initial) : fn(transformed);
50
+ transformed = unwrapValue(flow && index === 0 && Array.isArray(initial) ? fn(...initial) : fn(transformed), flow);
35
51
  }
36
52
  return transformed;
37
53
  }
38
- var MESSAGE_FLOW = "Flow expected to receive an array of functions";
39
- var MESSAGE_PIPE = "Pipe expected to receive an array of functions";
40
- var assertFlowFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_FLOW, TypeError);
41
- var assertPipeFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_PIPE, TypeError);
54
+ var MESSAGE_FLOW_ARRAY = "Flow expected to receive an array of functions";
55
+ var MESSAGE_FLOW_PROMISE = "Synchronous Flow received a promise. Use `flow.async` instead.";
56
+ var MESSAGE_NESTING = "Return values are too deeply nested.";
57
+ var MESSAGE_PIPE_ARRAY = "Pipe expected to receive an array of functions";
58
+ var MESSAGE_PIPE_PROMISE = "Synchronous Pipe received a promise. Use `pipe.async` instead.";
59
+ var assertFlowFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_FLOW_ARRAY, TypeError);
60
+ var assertPipeFunctions = assert.condition((value) => Array.isArray(value) && value.every((item) => typeof item === "function"), MESSAGE_PIPE_ARRAY, TypeError);
42
61
  export { flow, pipe };
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ import { exists } from "./array/exists.js";
2
2
  import { filter } from "./array/filter.js";
3
3
  import { find } from "./array/find.js";
4
4
  import { flatten } from "./array/flatten.js";
5
+ import { range, times } from "./array/from.js";
5
6
  import { isArrayOrPlainObject, isConstructor, isKey, isNumber, isPlainObject, isTypedArray } from "./internal/is.js";
6
7
  import { getArray } from "./array/get.js";
7
8
  import { groupBy } from "./array/group-by.js";
@@ -13,7 +14,6 @@ import { getRandomFloat, getRandomInteger } from "./internal/random.js";
13
14
  import { shuffle } from "./internal/array/shuffle.js";
14
15
  import { partition } from "./array/partition.js";
15
16
  import { push } from "./array/push.js";
16
- import { range } from "./array/range.js";
17
17
  import { select } from "./array/select.js";
18
18
  import { max } from "./internal/math/aggregate.js";
19
19
  import { getString, ignoreKey, join, tryDecode, tryEncode, words } from "./internal/string.js";
@@ -41,6 +41,7 @@ import { debounce } from "./function/debounce.js";
41
41
  import { SizedMap } from "./sized/map.js";
42
42
  import { memoize } from "./function/memoize.js";
43
43
  import { throttle } from "./function/throttle.js";
44
+ import { isError, isOk, isResult } from "./internal/result.js";
44
45
  import { flow, pipe } from "./function/work.js";
45
46
  import { equal } from "./internal/value/equal.js";
46
47
  import { getValue } from "./internal/value/get.js";
@@ -63,6 +64,6 @@ import { CancelablePromise, PromiseTimeoutError, attemptPromise, cancelable, del
63
64
  import { fromQuery, toQuery } from "./query.js";
64
65
  import { QueueError, queue } from "./queue.js";
65
66
  import { getRandomBoolean, getRandomCharacters, getRandomColor, getRandomHex, getRandomItem, getRandomItems } from "./random.js";
66
- import { attempt, error, isError, isOk, isResult, ok, unwrap } from "./result.js";
67
+ import { attempt, error, ok, unwrap } from "./result/index.js";
67
68
  import { SizedSet } from "./sized/set.js";
68
- export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, fromQuery, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
69
+ export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, fromQuery, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, times, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
@@ -0,0 +1,25 @@
1
+ import { isPlainObject } from "./is.js";
2
+ function _isResult(value, okValue) {
3
+ if (!isPlainObject(value)) return false;
4
+ return value.ok === okValue && (okValue ? "value" : "error") in value;
5
+ }
6
+ function isError(value, extended) {
7
+ return _isResult(value, false) && (extended === true ? value.original instanceof Error : true);
8
+ }
9
+ /**
10
+ * Is the result ok?
11
+ * @param result Result to check
12
+ * @returns `true` if the result is ok, `false` otherwise
13
+ */
14
+ function isOk(value) {
15
+ return _isResult(value, true);
16
+ }
17
+ /**
18
+ * Is the value a result?
19
+ * @param value Value to check
20
+ * @returns `true` if the value is a result, `false` otherwise
21
+ */
22
+ function isResult(value) {
23
+ return _isResult(value, true) || _isResult(value, false);
24
+ }
25
+ export { isError, isOk, isResult };
package/dist/random.js CHANGED
@@ -3,7 +3,7 @@ import { shuffle } from "./internal/array/shuffle.js";
3
3
  import { join } from "./internal/string.js";
4
4
  /**
5
5
  * Get a random boolean
6
- * @return Random boolean
6
+ * @returns Random boolean
7
7
  */
8
8
  function getRandomBoolean() {
9
9
  return Math.random() > BOOLEAN_MODIFIER;
@@ -1,9 +1,7 @@
1
- import { isPlainObject } from "./internal/is.js";
2
- import { attemptPromise } from "./promise.js";
3
- function _isResult(value, okValue) {
4
- if (!isPlainObject(value)) return false;
5
- return value.ok === okValue && (okValue ? "value" : "error") in value;
6
- }
1
+ import { isError, isOk, isResult } from "../internal/result.js";
2
+ import { attemptPromise } from "../promise.js";
3
+ import { attemptFlow } from "./work/flow.js";
4
+ import { attemptPipe } from "./work/pipe.js";
7
5
  async function asyncAttempt(value, err) {
8
6
  try {
9
7
  let result = typeof value === "function" ? value() : await value;
@@ -21,6 +19,8 @@ function attempt(callback, err) {
21
19
  }
22
20
  }
23
21
  attempt.async = asyncAttempt;
22
+ attempt.flow = attemptFlow;
23
+ attempt.pipe = attemptPipe;
24
24
  attempt.promise = attemptPromise;
25
25
  function error(value, original) {
26
26
  return getError(value, original);
@@ -33,25 +33,6 @@ function getError(value, original) {
33
33
  if (original instanceof Error) errorResult.original = original;
34
34
  return errorResult;
35
35
  }
36
- function isError(value, extended) {
37
- return _isResult(value, false) && (extended === true ? value.original instanceof Error : true);
38
- }
39
- /**
40
- * Is the result ok?
41
- * @param result Result to check
42
- * @returns `true` if the result is ok, `false` otherwise
43
- */
44
- function isOk(value) {
45
- return _isResult(value, true);
46
- }
47
- /**
48
- * Is the value a result?
49
- * @param value Value to check
50
- * @returns `true` if the value is a result, `false` otherwise
51
- */
52
- function isResult(value) {
53
- return _isResult(value, true) || _isResult(value, false);
54
- }
55
36
  /**
56
37
  * Creates an ok result
57
38
  * @param value Value
File without changes
@@ -0,0 +1,25 @@
1
+ import { isError, isOk } from "../../internal/result.js";
2
+ import { flow } from "../../function/work.js";
3
+ import { attempt } from "../index.js";
4
+ function attemptAsyncFlow(...fns) {
5
+ let Flow;
6
+ return (...args) => attempt.async(() => {
7
+ Flow ??= flow.async(...fns);
8
+ return Flow(...args.map((value) => {
9
+ if (isError(value)) throw value.error;
10
+ return isOk(value) ? value.value : value;
11
+ }));
12
+ });
13
+ }
14
+ function attemptFlow(...fns) {
15
+ let Flow;
16
+ return (...args) => attempt(() => {
17
+ Flow ??= flow(...fns);
18
+ return Flow(...args.map((value) => {
19
+ if (isError(value)) throw value.error;
20
+ return isOk(value) ? value.value : value;
21
+ }));
22
+ });
23
+ }
24
+ attemptFlow.async = attemptAsyncFlow;
25
+ export { attemptFlow };
@@ -0,0 +1,21 @@
1
+ import { isError, isOk } from "../../internal/result.js";
2
+ import { pipe } from "../../function/work.js";
3
+ import { attempt } from "../index.js";
4
+ async function attemptAsyncPipe(initial, first, ...seconds) {
5
+ return attempt.async(() => {
6
+ if (isError(initial)) throw initial.error;
7
+ const value = typeof initial === "function" ? initial() : isOk(initial) ? initial.value : initial;
8
+ if (first == null) return value;
9
+ return pipe.async(value, ...[first, ...seconds]);
10
+ });
11
+ }
12
+ function attemptPipe(initial, first, ...seconds) {
13
+ return attempt(() => {
14
+ if (isError(initial)) throw initial.error;
15
+ const value = typeof initial === "function" ? initial() : isOk(initial) ? initial.value : initial;
16
+ if (first == null) return value;
17
+ return pipe(value, ...[first, ...seconds]);
18
+ });
19
+ }
20
+ attemptPipe.async = attemptAsyncPipe;
21
+ export { attemptPipe };
package/package.json CHANGED
@@ -110,8 +110,8 @@
110
110
  "default": "./dist/random.js"
111
111
  },
112
112
  "./result": {
113
- "types": "./types/result.d.ts",
114
- "default": "./dist/result.js"
113
+ "types": "./types/result/index.d.ts",
114
+ "default": "./dist/result/index.js"
115
115
  },
116
116
  "./sized/map": {
117
117
  "types": "./types/sized/map.d.ts",
@@ -192,5 +192,5 @@
192
192
  },
193
193
  "type": "module",
194
194
  "types": "./types/index.d.ts",
195
- "version": "0.146.0"
195
+ "version": "0.148.0"
196
196
  }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Get an array with a specified length, filled with indices
3
+ * @param length Length of the array
4
+ * @returns Array of indices
5
+ */
6
+ export function range(length: number): number[];
7
+
8
+ /**
9
+ * Get an array of numbers in a specified range
10
+ * @param start Starting number _(inclusive)_
11
+ * @param end Ending number _(exclusive)_
12
+ * @returns Array of numbers in range
13
+ */
14
+ export function range(start: number, end: number): number[];
15
+
16
+ /**
17
+ * Get an array of numbers in a specified range with a specified step
18
+ * @param start Starting number _(inclusive)_
19
+ * @param end Ending number _(exclusive)_
20
+ * @param step Step between numbers
21
+ * @returns Array of numbers in range
22
+ */
23
+ export function range(start: number, end: number, step: number): number[];
24
+
25
+ export function range(first: number, second?: number, third?: number): number[] {
26
+ const start = typeof second === 'number' ? first : 0;
27
+ const end = typeof second === 'number' ? second : first;
28
+ const step = typeof third === 'number' ? third : 1;
29
+
30
+ const values: number[] = [];
31
+
32
+ if (step === 0) {
33
+ return values;
34
+ }
35
+
36
+ if (step > 0) {
37
+ for (let i = start; i < end; i += step) {
38
+ values.push(i);
39
+ }
40
+ } else {
41
+ for (let i = start; i > end; i += step) {
42
+ values.push(i);
43
+ }
44
+ }
45
+
46
+ return values;
47
+ }
48
+
49
+ /**
50
+ * Get an array with a specified length, filled with indices
51
+ * @param length Length of the array
52
+ * @returns Array of indices
53
+ */
54
+ export function times(length: number): number[];
55
+
56
+ /**
57
+ * Get an array with a specified length, filled by values from a callback
58
+ * @param length Length of the array
59
+ * @param callback Callback function to generate values
60
+ * @returns Array of values generated by the callback
61
+ */
62
+ export function times<Callback extends (index: number) => unknown>(
63
+ length: number,
64
+ callback: Callback,
65
+ ): ReturnType<Callback>[];
66
+
67
+ /**
68
+ * Get an array with a specified length, filled with a specified value
69
+ * @param length Length of the array
70
+ * @param value Value to fill the array with
71
+ * @returns Array filled with the specified value
72
+ */
73
+ export function times<Value>(length: number, value: Value): Value[];
74
+
75
+ export function times(length: number, value?: unknown): unknown[] {
76
+ if (typeof length !== 'number' || length <= 0) {
77
+ return [];
78
+ }
79
+
80
+ const isFunction = typeof value === 'function';
81
+
82
+ const values: unknown[] = [];
83
+
84
+ for (let index = 0; index < length; index += 1) {
85
+ values.push(isFunction ? (value as (index: number) => unknown)(index) : (value ?? index));
86
+ }
87
+
88
+ return values;
89
+ }
package/src/array/misc.ts CHANGED
@@ -6,12 +6,12 @@ export * from './exists';
6
6
  export * from './filter';
7
7
  export * from './find';
8
8
  export * from './flatten';
9
+ export * from './from';
9
10
  export * from './get';
10
11
  export * from './index-of';
11
12
  export * from './insert';
12
13
  export * from './partition';
13
14
  export * from './push';
14
- export * from './range';
15
15
  export * from './select';
16
16
  export * from './sort';
17
17
  export * from './splice';
@@ -6,7 +6,7 @@ import type {PlainObject} from '../models';
6
6
  * @param destination Array to toggle within
7
7
  * @param toggled Toggled items
8
8
  * @param callback Callback to find existing item
9
- * @return Original array
9
+ * @returns Original array
10
10
  */
11
11
  export function toggle<Item>(
12
12
  destination: Item[],
@@ -19,7 +19,7 @@ export function toggle<Item>(
19
19
  * @param destination Array to toggle within
20
20
  * @param toggled Toggled items
21
21
  * @param key Key to find existing item
22
- * @return Original array
22
+ * @returns Original array
23
23
  */
24
24
  export function toggle<Item extends PlainObject, Key extends keyof Item>(
25
25
  destination: Item[],