@gkucmierz/utils 3.0.1 → 3.1.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.
package/README.md CHANGED
@@ -45,14 +45,25 @@ This library provides a wide range of mathematical functions and data structures
45
45
  - `squareRoot`: Integer square root using Newton's method.
46
46
  - `goldenRatio`, `goldenRatioBI`: The Golden Ratio calculation (with arbitrary precision support).
47
47
 
48
+ - **Optimization & Machine Learning**:
49
+ - `nelderMead`: Nelder-Mead (simplex) optimization algorithm for multi-dimensional functions.
50
+ - `particleSwarmOptimization`: PSO algorithm for global optimization.
51
+ - `simulatedAnnealing`: Probabilistic technique for approximating the global optimum of a given function.
52
+
53
+ - **Math & 3D Geometry**:
54
+ - `math3d`: Utilities for 3D vector and matrix math (`crossProduct`, `dotProduct`, `normalize`, `multiplyMatrix4`, `projectToTrackball`, `getRotationMatrixFromVectors`).
55
+ - `randNormal`: Normal (Gaussian) distribution random number generator (Box-Muller transform).
56
+
48
57
  - **Automata & Simulation**:
49
58
  - `createLangtonsAnt`, `createUnlimitedGrid`: Infinite 2D grid and Langton's Ant cellular automaton engine (Project Euler 349 compatible).
50
59
 
51
60
  - **String & Encoding & Arrays**:
61
+ - `chunks`, `chunksIterator`, `chunksAsyncIterator`: Synchronous and asynchronous array/string chunking generators.
52
62
  - `base64`: Base64 and Base64Url encoding/decoding.
53
63
  - `copyCase`: Match case of a string to another.
54
64
  - `arrayHistogram`: Creates Map mappings counting absolute frequencies across any `Iterable`.
55
65
  - `bijectiveNumeration`: Bijective base-k numeration system.
66
+ - `formatBigNumber`: Intelligent formatting for massively large numbers with suffixes.
56
67
 
57
68
  - **Developer Utilities**:
58
69
  - `measurePerformance`: A micro-benchmarking tool for high-iteration performance testing.
@@ -60,6 +71,7 @@ This library provides a wide range of mathematical functions and data structures
60
71
  - `consumeIteratorNonBlocking`: Yield consumption macro-tasks queue resolver for heavy computations.
61
72
  - `memoize`: Function memoization based on arguments.
62
73
  - `binarySearch`: Various binary search implementations (exact, lower bound, upper bound).
74
+ - `naturalSearch`: Natural sorting/search utility for human-readable string comparisons.
63
75
  - `range2array`, `array2range`: Convert between ranges and arrays.
64
76
  - `getType`: Precise dynamic type checking.
65
77
 
package/main.mjs CHANGED
@@ -17,6 +17,9 @@ import {
17
17
  import {
18
18
  binarySearchArr, binarySearchGE, binarySearchLE, binarySearchRangeIncl
19
19
  } from './src/binary-search.mjs'
20
+ import {
21
+ chunks, chunksAsyncIterator, chunksIterator
22
+ } from './src/chunks.mjs'
20
23
  import {
21
24
  combinations, combinationsIterator
22
25
  } from './src/combinations.mjs'
@@ -42,7 +45,7 @@ import {
42
45
  getType
43
46
  } from './src/get-type.mjs'
44
47
  import {
45
- goldenRatio, goldenRatioBI
48
+ goldenRatio, goldenRatioBI, goldenRatioStr
46
49
  } from './src/golden-ratio.mjs'
47
50
  import {
48
51
  gpn, gpnBI
@@ -129,6 +132,7 @@ export * from './src/array-histogram.mjs';
129
132
  export * from './src/base64.mjs';
130
133
  export * from './src/bijective-numeration.mjs';
131
134
  export * from './src/binary-search.mjs';
135
+ export * from './src/chunks.mjs';
132
136
  export * from './src/combinations.mjs';
133
137
  export * from './src/consume-iterator.mjs';
134
138
  export * from './src/copy-case.mjs';
@@ -166,5 +170,5 @@ export * from './src/square-root.mjs';
166
170
  export * from './src/tonelli-shanks.mjs';
167
171
 
168
172
  export default [
169
- SetCnt, Trie, arrayHistogram, fromBase64, fromBase64Url, toBase64, toBase64Url, bijective2num, bijective2numBI, num2bijective, num2bijectiveBI, binarySearchArr, binarySearchGE, binarySearchLE, binarySearchRangeIncl, combinations, combinationsIterator, consumeIteratorNonBlocking, copyCase, egcd, factors, factorsBI, formatBigNumber, formatBigNumberBI, wrapFn, gcd, gcdBI, getType, goldenRatio, goldenRatioBI, gpn, gpnBI, bin2gray, gray2bin, Heap, heronsFormula, heronsFormulaBI, createLangtonsAnt, createUnlimitedGrid, lcm, lcmBI, ListNode, lucasLehmerBI, axisAngleToMatrix4, crossProduct, dotProduct, getRotationMatrixFromVectors, multiplyMatrix4, normalize, projectToTrackball, matrixAsArray, measurePerformance, memoize, mod, modBI, nChooseK, naturalSearch, nelderMead, particleSwarmOptimization, permutations, permutationsIterator, phi, phiBI, powMod, powModBI, randNormal, array2range, range2array, setSafeInterval, simulatedAnnealing, squareRoot, squareRootBI, tonelliShanksBI
173
+ SetCnt, Trie, arrayHistogram, fromBase64, fromBase64Url, toBase64, toBase64Url, bijective2num, bijective2numBI, num2bijective, num2bijectiveBI, binarySearchArr, binarySearchGE, binarySearchLE, binarySearchRangeIncl, chunks, chunksAsyncIterator, chunksIterator, combinations, combinationsIterator, consumeIteratorNonBlocking, copyCase, egcd, factors, factorsBI, formatBigNumber, formatBigNumberBI, wrapFn, gcd, gcdBI, getType, goldenRatio, goldenRatioBI, goldenRatioStr, gpn, gpnBI, bin2gray, gray2bin, Heap, heronsFormula, heronsFormulaBI, createLangtonsAnt, createUnlimitedGrid, lcm, lcmBI, ListNode, lucasLehmerBI, axisAngleToMatrix4, crossProduct, dotProduct, getRotationMatrixFromVectors, multiplyMatrix4, normalize, projectToTrackball, matrixAsArray, measurePerformance, memoize, mod, modBI, nChooseK, naturalSearch, nelderMead, particleSwarmOptimization, permutations, permutationsIterator, phi, phiBI, powMod, powModBI, randNormal, array2range, range2array, setSafeInterval, simulatedAnnealing, squareRoot, squareRootBI, tonelliShanksBI
170
174
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gkucmierz/utils",
3
- "version": "3.0.1",
3
+ "version": "3.1.0",
4
4
  "type": "module",
5
5
  "description": "Usefull functions for solving programming tasks",
6
6
  "keywords": [
@@ -44,7 +44,15 @@
44
44
  "square-root",
45
45
  "tonelli-shanks",
46
46
  "trie",
47
- "utils"
47
+ "utils",
48
+ "chunks",
49
+ "math3d",
50
+ "nelder-mead",
51
+ "particle-swarm",
52
+ "simulated-annealing",
53
+ "rand-normal",
54
+ "format-big-number",
55
+ "natural-search"
48
56
  ],
49
57
  "files": [
50
58
  "main.mjs",
package/src/chunks.mjs ADDED
@@ -0,0 +1,64 @@
1
+ export const chunks = (input, size = 1) => {
2
+ if (size < 1) size = 1;
3
+
4
+ if (typeof input === 'string' || Array.isArray(input)) {
5
+ const numChunks = Math.ceil(input.length / size);
6
+ const result = new Array(numChunks);
7
+ for (let i = 0, offset = 0; i < numChunks; ++i, offset += size) {
8
+ result[i] = input.slice(offset, offset + size);
9
+ }
10
+ return result;
11
+ }
12
+
13
+ // Fallback for other synchronous iterables (Sets, Maps, custom iterators)
14
+ const result = [];
15
+ let currentChunk = [];
16
+ for (const item of input) {
17
+ currentChunk.push(item);
18
+ if (currentChunk.length === size) {
19
+ result.push(currentChunk);
20
+ currentChunk = [];
21
+ }
22
+ }
23
+ if (currentChunk.length > 0) {
24
+ result.push(currentChunk);
25
+ }
26
+ return result;
27
+ };
28
+
29
+ export function* chunksIterator(iterable, size = 1) {
30
+ if (size < 1) size = 1;
31
+
32
+ const isString = typeof iterable === 'string';
33
+ let currentChunk = [];
34
+
35
+ for (const item of iterable) {
36
+ currentChunk.push(item);
37
+ if (currentChunk.length === size) {
38
+ yield isString ? currentChunk.join('') : currentChunk;
39
+ currentChunk = [];
40
+ }
41
+ }
42
+
43
+ if (currentChunk.length > 0) {
44
+ yield isString ? currentChunk.join('') : currentChunk;
45
+ }
46
+ }
47
+
48
+ export async function* chunksAsyncIterator(asyncIterable, size = 1) {
49
+ if (size < 1) size = 1;
50
+
51
+ let currentChunk = [];
52
+
53
+ for await (const item of asyncIterable) {
54
+ currentChunk.push(item);
55
+ if (currentChunk.length === size) {
56
+ yield currentChunk;
57
+ currentChunk = [];
58
+ }
59
+ }
60
+
61
+ if (currentChunk.length > 0) {
62
+ yield currentChunk;
63
+ }
64
+ }
@@ -9,11 +9,9 @@ export const goldenRatio = ((5 ** 0.5) + 1) / 2;
9
9
 
10
10
  /**
11
11
  * Calculates the Golden Ratio (phi) to an arbitrary precision using BigInt.
12
- * Returns a boxed BigInt object with an overridden toString() method to
13
- * automatically format the output with the correct decimal point placement.
14
12
  *
15
13
  * @param {number|bigint} precision - The number of decimal places to calculate.
16
- * @returns {BigInt} A boxed BigInt representing the Golden Ratio scaled by 10^precision.
14
+ * @returns {BigInt} A primitive BigInt representing the Golden Ratio scaled by 10^precision.
17
15
  * @throws {Error} If precision is negative.
18
16
  * @see {@link https://instacode.app/run/FASwtgDg9gTgLgAgN4IOZQDYBMCmA7AJQEM4QoAhASQQF8EAzGKMBAIgAFUBrAVwGMwIHDABeAeh6kMAZ1YBuYMHTZ8xUhUoKgA|▶ Try it live in Instacode}
19
17
  */
@@ -24,17 +22,22 @@ export const goldenRatioBI = precision => {
24
22
 
25
23
  // (sqrt(5 * exp^2) + exp) / 2
26
24
  const result = (squareRootBI(5n * exp * exp) + exp) / 2n;
25
+ return result;
26
+ };
27
+
28
+ /**
29
+ * Calculates the Golden Ratio (phi) to an arbitrary precision and returns it as a formatted string.
30
+ * @param {number|bigint} precision - The number of decimal places to calculate.
31
+ * @returns {string} The formatted Golden Ratio string (e.g., '1.618...').
32
+ * @throws {Error} If precision is negative.
33
+ * @see {@link https://instacode.app/run/FASwtgDg9gTgLgAgN4IOZQDYBMCmA7AJQEM4QoBlOGBAXwQDMYowEAiAAVQGsBXAYzAgcMAF4B6HqQwBnVgG5gwdNnzFSFKgqA|▶ Try it live in Instacode}
34
+ */
35
+ export const goldenRatioStr = precision => {
36
+ if (precision < 0) throw new Error('Precision cannot be negative');
37
+ const str = goldenRatioBI(precision).toString();
38
+ if (precision === 0 || precision === 0n) return str;
27
39
 
28
- // Wrap primitive BigInt in an Object (Boxing)
29
- const boxedResult = Object(result);
30
- boxedResult.toString = () => {
31
- const str = result.toString();
32
- if (precision === 0) return str;
33
-
34
- // The Golden Ratio is ~1.618, so the integer part is always '1'.
35
- // The length of str is exactly precision + 1.
36
- return str.slice(0, 1) + '.' + str.slice(1);
37
- };
38
-
39
- return boxedResult;
40
+ // The Golden Ratio is ~1.618, so the integer part is always '1'.
41
+ // The length of str is exactly precision + 1.
42
+ return str.slice(0, 1) + '.' + str.slice(1);
40
43
  };