@gkucmierz/utils 2.0.8 → 2.3.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
@@ -47,6 +47,10 @@ This library provides a wide range of mathematical functions and data structures
47
47
  - `gpn`: Generalized Pentagonal Numbers.
48
48
  - `heronsFormula`: Triangle area calculation.
49
49
  - `squareRoot`: Integer square root using Newton's method.
50
+ - `goldenRatio`, `goldenRatioBI`: The Golden Ratio calculation (with arbitrary precision support).
51
+
52
+ - **Automata & Simulation**:
53
+ - `createLangtonsAnt`, `createUnlimitedGrid`: Infinite 2D grid and Langton's Ant cellular automaton engine (Project Euler 349 compatible).
50
54
 
51
55
  - **String & Encoding & Arrays**:
52
56
  - `base64`: Base64 and Base64Url encoding/decoding.
@@ -55,6 +59,7 @@ This library provides a wide range of mathematical functions and data structures
55
59
  - `bijectiveNumeration`: Bijective base-k numeration system.
56
60
 
57
61
  - **Developer Utilities**:
62
+ - `measurePerformance`: A micro-benchmarking tool for high-iteration performance testing.
58
63
  - `setSafeInterval`: A safe, asynchronous alternative to `setInterval` that prevents overlapping executions and supports immediate yielding.
59
64
  - `consumeIteratorNonBlocking`: Yield consumption macro-tasks queue resolver for heavy computations.
60
65
  - `memoize`: Function memoization based on arguments.
package/main.mjs CHANGED
@@ -41,6 +41,9 @@ import {
41
41
  import {
42
42
  getType
43
43
  } from './src/get-type.mjs'
44
+ import {
45
+ goldenRatio, goldenRatioBI
46
+ } from './src/golden-ratio.mjs'
44
47
  import {
45
48
  gpn, gpnBI
46
49
  } from './src/gpn.mjs'
@@ -53,6 +56,9 @@ import {
53
56
  import {
54
57
  heronsFormula, heronsFormulaBI
55
58
  } from './src/herons-formula.mjs'
59
+ import {
60
+ createLangtonsAnt, createUnlimitedGrid
61
+ } from './src/langtons-ant.mjs'
56
62
  import {
57
63
  lcm, lcmBI
58
64
  } from './src/lcm.mjs'
@@ -68,6 +74,9 @@ import {
68
74
  import {
69
75
  matrixAsArray
70
76
  } from './src/matrix.mjs'
77
+ import {
78
+ measurePerformance
79
+ } from './src/measure-performance.mjs'
71
80
  import {
72
81
  memoize
73
82
  } from './src/memoize.mjs'
@@ -128,15 +137,18 @@ export * from './src/factors.mjs';
128
137
  export * from './src/format-big-number.mjs';
129
138
  export * from './src/gcd.mjs';
130
139
  export * from './src/get-type.mjs';
140
+ export * from './src/golden-ratio.mjs';
131
141
  export * from './src/gpn.mjs';
132
142
  export * from './src/gray-code.mjs';
133
143
  export * from './src/heap.mjs';
134
144
  export * from './src/herons-formula.mjs';
145
+ export * from './src/langtons-ant.mjs';
135
146
  export * from './src/lcm.mjs';
136
147
  export * from './src/list-node.mjs';
137
148
  export * from './src/lucas-lehmer.mjs';
138
149
  export * from './src/math3d.mjs';
139
150
  export * from './src/matrix.mjs';
151
+ export * from './src/measure-performance.mjs';
140
152
  export * from './src/memoize.mjs';
141
153
  export * from './src/mod.mjs';
142
154
  export * from './src/n-choose-k.mjs';
@@ -154,5 +166,5 @@ export * from './src/square-root.mjs';
154
166
  export * from './src/tonelli-shanks.mjs';
155
167
 
156
168
  export default [
157
- 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, gpn, gpnBI, bin2gray, gray2bin, Heap, heronsFormula, heronsFormulaBI, lcm, lcmBI, ListNode, lucasLehmerBI, axisAngleToMatrix4, crossProduct, dotProduct, getRotationMatrixFromVectors, multiplyMatrix4, normalize, projectToTrackball, matrixAsArray, memoize, mod, modBI, nChooseK, naturalSearch, nelderMead, particleSwarmOptimization, permutations, permutationsIterator, phi, phiBI, powMod, powModBI, randNormal, array2range, range2array, setSafeInterval, simulatedAnnealing, squareRoot, squareRootBI, tonelliShanksBI
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
158
170
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gkucmierz/utils",
3
- "version": "2.0.8",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "description": "Usefull functions for solving programming tasks",
6
6
  "keywords": [
@@ -9,18 +9,22 @@
9
9
  "base64",
10
10
  "bijective",
11
11
  "binary-search",
12
+ "benchmark",
12
13
  "combinations",
13
14
  "competitive-programming",
14
15
  "data-structures",
15
16
  "factors",
16
17
  "gcd",
18
+ "golden-ratio",
17
19
  "gray-code",
18
20
  "heap",
19
21
  "iterator",
20
22
  "javascript",
21
23
  "lcm",
24
+ "langtons-ant",
22
25
  "lucas-lehmer",
23
26
  "math",
27
+ "cellular-automaton",
24
28
  "memoize",
25
29
  "mersenne",
26
30
  "mod",
@@ -0,0 +1,38 @@
1
+ import { squareRootBI } from './square-root.mjs';
2
+
3
+ /**
4
+ * The standard float approximation of the Golden Ratio (phi).
5
+ * @constant {number}
6
+ */
7
+ export const goldenRatio = ((5 ** 0.5) + 1) / 2;
8
+
9
+ /**
10
+ * Calculates the Golden Ratio (phi) to an arbitrary precision using BigInt.
11
+ * Returns a boxed BigInt object with an overridden toString() method to
12
+ * automatically format the output with the correct decimal point placement.
13
+ *
14
+ * @param {number|bigint} precision - The number of decimal places to calculate.
15
+ * @returns {BigInt} A boxed BigInt representing the Golden Ratio scaled by 10^precision.
16
+ * @throws {Error} If precision is negative.
17
+ */
18
+ export const goldenRatioBI = precision => {
19
+ if (precision < 0) throw new Error('Precision cannot be negative');
20
+ const p = BigInt(precision);
21
+ const exp = 10n ** p;
22
+
23
+ // (sqrt(5 * exp^2) + exp) / 2
24
+ const result = (squareRootBI(5n * exp * exp) + exp) / 2n;
25
+
26
+ // Wrap primitive BigInt in an Object (Boxing)
27
+ const boxedResult = Object(result);
28
+ boxedResult.toString = function() {
29
+ const str = this.valueOf().toString();
30
+ if (precision === 0) return str;
31
+
32
+ // The Golden Ratio is ~1.618, so the integer part is always '1'.
33
+ // The length of str is exactly precision + 1.
34
+ return str.slice(0, 1) + '.' + str.slice(1);
35
+ };
36
+
37
+ return boxedResult;
38
+ };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Creates an unlimited, dynamically expanding 2D grid using nested Maps.
3
+ * Ideal for sparse matrices or algorithms operating on an infinite plane (e.g., Langton's Ant, Game of Life).
4
+ *
5
+ * @returns {Object} An object containing `get(x, y)` and `set(x, y, val)` methods.
6
+ */
7
+ export const createUnlimitedGrid = () => {
8
+ const grid = new Map();
9
+
10
+ const getRow = y => {
11
+ let row;
12
+ if (!(row = grid.get(y))) {
13
+ row = new Map();
14
+ grid.set(y, row);
15
+ }
16
+ return row;
17
+ };
18
+
19
+ const set = (x, y, val) => {
20
+ const row = getRow(y);
21
+ row.set(x, val);
22
+ };
23
+
24
+ const get = (x, y) => {
25
+ const row = getRow(y);
26
+ return row.get(x) || 0;
27
+ };
28
+
29
+ return { set, get };
30
+ };
31
+
32
+ /**
33
+ * Initializes a Langton's Ant automaton on a given grid.
34
+ * The ant follows standard rules: turns right on 0, turns left on 1, and flips the cell state.
35
+ *
36
+ * @param {Object} grid - The grid interface containing `get(x, y)` and `set(x, y, val)` methods.
37
+ * @param {number} startX - The initial X coordinate of the ant.
38
+ * @param {number} startY - The initial Y coordinate of the ant.
39
+ * @param {number} [initialDir=-1] - The initial direction (0: TOP, 1: RIGHT, 2: BOTTOM, 3: LEFT). If -1, a random direction is chosen.
40
+ * @returns {Object} An object containing a `step()` method which advances the simulation by one tick and returns `{x, y, state}` of the modified cell.
41
+ */
42
+ export const createLangtonsAnt = (grid, startX, startY, initialDir = -1) => {
43
+ const [X, Y] = [0, 1];
44
+ const [TOP, RIGHT, BOT, LEFT] = [0, 1, 2, 3];
45
+ const coordMap = new Map([
46
+ [TOP, [ 0,-1]],
47
+ [RIGHT, [ 1, 0]],
48
+ [BOT, [ 0, 1]],
49
+ [LEFT, [-1, 0]],
50
+ ]);
51
+
52
+ let dir = initialDir !== -1 ? initialDir : Math.floor(Math.random() * 4);
53
+ const pos = [startX, startY];
54
+
55
+ const step = () => {
56
+ const currentState = grid.get(pos[X], pos[Y]);
57
+ const nextState = currentState === 0 ? 1 : 0;
58
+
59
+ grid.set(pos[X], pos[Y], nextState);
60
+
61
+ if (currentState === 0) {
62
+ dir = (dir + 1) % 4; // Turn Right
63
+ } else {
64
+ dir = (dir + 3) % 4; // Turn Left
65
+ }
66
+
67
+ const move = coordMap.get(dir);
68
+ pos[X] += move[X];
69
+ pos[Y] += move[Y];
70
+
71
+ return {
72
+ x: pos[X] - move[X],
73
+ y: pos[Y] - move[Y],
74
+ state: nextState
75
+ };
76
+ };
77
+
78
+ return { step };
79
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Measures the execution time of a given function by running it multiple times.
3
+ * Useful for micro-benchmarking and performance comparison.
4
+ *
5
+ * @param {Function} fn - The function to benchmark.
6
+ * @param {number} [times=1e8] - The number of iterations to run the function.
7
+ * @param {string} [memo='noop'] - A descriptive label for the benchmark result.
8
+ * @returns {Object} An object containing the `memo` and the `duration` (in milliseconds).
9
+ */
10
+ export const measurePerformance = (fn, times = 1e8, memo = 'noop') => {
11
+ const t1 = Date.now();
12
+ while (times--) {
13
+ fn();
14
+ }
15
+ const t2 = Date.now();
16
+
17
+ return {
18
+ memo,
19
+ duration: t2 - t1
20
+ };
21
+ };