Gathering detailed insights and metrics for @andranik-arakelyan/js-utilities
Gathering detailed insights and metrics for @andranik-arakelyan/js-utilities
Gathering detailed insights and metrics for @andranik-arakelyan/js-utilities
Gathering detailed insights and metrics for @andranik-arakelyan/js-utilities
Zero-dependency TypeScript utility functions that enhance JavaScript's standard library.
npm install @andranik-arakelyan/js-utilities
Typescript
Module System
Node Version
NPM Version
TypeScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
68 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Jul 15, 2025
Latest Version
0.14.0
Package Id
@andranik-arakelyan/js-utilities@0.14.0
Unpacked Size
66.90 kB
Size
18.61 kB
File Count
63
NPM Version
11.2.0
Node Version
22.11.0
Published on
Jul 15, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
8
Utility functions for all JavaScript/TypeScript environments.
To install the package, use npm:
1npm install @andranik-arakelyan/js-utilities
Import the utilities you need in your project:
1import {arraySubtract} from '@andranik-arakelyan/js-utilities'; 2 3const result = arraySubtract([1, 3, 5] , [ 1, 2, 3]); 4console.log( 'result', result ); // [5]
A generic type-safe implementation of a Stack data structure with LIFO (Last-In-First-Out) operations.
1import { Stack } from '@andranik-arakelyan/js-utilities'; 2 3// Create a new stack of numbers 4const stack = new Stack<number>(); 5 6// Push elements onto the stack 7stack.push(1); 8stack.push(2); 9stack.push(3); 10 11console.log(stack.peek()); // 3 (returns the top element without removing it) 12console.log(stack.pop()); // 3 (removes and returns the top element) 13console.log(stack.size()); // 2 (returns the current number of elements) 14console.log(stack.isEmpty()); // false
A generic type-safe implementation of a Queue data structure with FIFO (First-In-First-Out) operations.
1import { Queue } from '@andranik-arakelyan/js-utilities'; 2 3// Create a new queue of strings 4const queue = new Queue<string>(); 5 6// Enqueue elements 7queue.enqueue("first"); 8queue.enqueue("second"); 9queue.enqueue("third"); 10 11console.log(queue.peek()); // "first" (returns the front element without removing it) 12console.log(queue.dequeue()); // "first" (removes and returns the front element) 13console.log(queue.size()); // 2 (returns the current number of elements) 14console.log(queue.isEmpty()); // false
A fixed-size circular buffer (ring buffer) that overwrites the oldest elements when the buffer is full and new elements are added. Perfect for implementing sliding windows, recent activity logs, and rolling metrics.
1import { CircularBuffer } from '@andranik-arakelyan/js-utilities'; 2 3// Create a circular buffer with capacity of 3 4const buffer = new CircularBuffer<number>(3); 5 6// Add elements normally at first 7buffer.push(1); // [1] 8buffer.push(2); // [1, 2] 9buffer.push(3); // [1, 2, 3] - buffer is now full 10 11// When full, new elements overwrite oldest 12buffer.push(4); // [2, 3, 4] - '1' was overwritten 13buffer.push(5); // [3, 4, 5] - '2' was overwritten 14 15console.log(buffer.toArray()); // [3, 4, 5] 16console.log(buffer.size()); // 3 17console.log(buffer.capacity()); // 3 18console.log(buffer.isFull()); // true 19 20// Access elements 21console.log(buffer.get(0)); // 3 (oldest element) 22console.log(buffer.peek()); // 5 (newest element) 23console.log(buffer.peekOldest()); // 3 (oldest element) 24 25// Remove oldest element 26const oldest = buffer.shift(); // 3 27console.log(buffer.toArray()); // [4, 5] 28 29// Clear all elements 30buffer.clear(); 31console.log(buffer.isEmpty()); // true 32 33// Works with any data type 34const logBuffer = new CircularBuffer<{timestamp: Date, message: string}>(100); 35logBuffer.push({timestamp: new Date(), message: "User logged in"}); 36 37// Iterable with for...of 38for (const item of buffer) { 39 console.log(item); 40}
Use Cases:
Subtracts elements of one array from another.
1import { arraySubtract } from '@andranik-arakelyan/js-utilities'; 2 3const arr1 = [1, 2, 3, 4, 5]; 4const arr2 = [1, 3, 5]; 5const result = arraySubtract(arr1, arr2); 6console.log(result); // [2, 4]
Splits an array into chunks based on a separator.
1import { arraySplit } from '@andranik-arakelyan/js-utilities'; 2 3// Using a value as separator 4const result1 = arraySplit([1, 2, 3, 0, 4, 5, 0, 6], 0); 5console.log(result1); // [[1, 2, 3], [4, 5], [6]] 6 7// Using a function as separator 8const result2 = arraySplit([1, 2, 3, 4, 5, 6], (item) => item % 2 === 0); 9console.log(result2); // [[1], [3], [5]]
Randomly shuffles an array using the Fisher-Yates algorithm. This algorithm is superior to naive shuffling approaches (like sorting with a random comparator) because it guarantees a truly random permutation with equal probability for each possible outcome and has optimal O(n) time complexity.
1import { shuffle } from '@andranik-arakelyan/js-utilities'; 2 3const array = [1, 2, 3, 4, 5]; 4const shuffled = shuffle(array); 5console.log(shuffled); // Example output: [3, 1, 5, 2, 4] 6console.log(array); // Original array remains unchanged: [1, 2, 3, 4, 5]
Returns a new array with duplicate values removed. Optionally accepts a function to determine the key for uniqueness comparison.
1import { unique } from '@andranik-arakelyan/js-utilities'; 2 3// Remove duplicates from primitive values 4const numbers = [1, 2, 2, 3, 1, 4]; 5console.log(unique(numbers)); // [1, 2, 3, 4] 6 7// With objects using a custom key selector 8const users = [ 9 { id: 1, name: 'Alice' }, 10 { id: 2, name: 'Bob' }, 11 { id: 1, name: 'Alice (duplicate)' } 12]; 13const uniqueUsers = unique(users, user => user.id); 14console.log(uniqueUsers); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
Groups array elements by a key selector function. Returns a Map where keys are the result of the key selector function and values are arrays of elements that share the same key.
1import { groupBy } from '@andranik-arakelyan/js-utilities'; 2 3// Group numbers by even/odd 4const numbers = [1, 2, 3, 4, 5, 6]; 5const grouped = groupBy(numbers, n => n % 2 === 0 ? 'even' : 'odd'); 6console.log(grouped); // Map { 'odd' => [1, 3, 5], 'even' => [2, 4, 6] } 7 8// Group objects by property 9const users = [ 10 { name: 'Alice', department: 'Engineering' }, 11 { name: 'Bob', department: 'Marketing' }, 12 { name: 'Charlie', department: 'Engineering' } 13]; 14const byDepartment = groupBy(users, user => user.department); 15console.log(byDepartment); 16// Map { 17// 'Engineering' => [ 18// { name: 'Alice', department: 'Engineering' }, 19// { name: 'Charlie', department: 'Engineering' } 20// ], 21// 'Marketing' => [{ name: 'Bob', department: 'Marketing' }] 22// } 23 24// Group by multiple criteria using composite keys 25const products = [ 26 { name: 'Laptop', category: 'Electronics', inStock: true }, 27 { name: 'Phone', category: 'Electronics', inStock: false }, 28 { name: 'Desk', category: 'Furniture', inStock: true } 29]; 30const byStatus = groupBy(products, p => `${p.category}-${p.inStock}`); 31// Groups by category and stock status combined
Splits an array into chunks of a specified size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size.
1import { chunk } from '@andranik-arakelyan/js-utilities'; 2 3// Basic usage with numbers 4const numbers = [1, 2, 3, 4, 5, 6]; 5const chunked = chunk(numbers, 2); 6console.log(chunked); // [[1, 2], [3, 4], [5, 6]] 7 8// Handle arrays not evenly divisible 9const oddLength = [1, 2, 3, 4, 5]; 10const chunkedOdd = chunk(oddLength, 2); 11console.log(chunkedOdd); // [[1, 2], [3, 4], [5]] 12 13// With objects 14const users = [ 15 { id: 1, name: 'Alice' }, 16 { id: 2, name: 'Bob' }, 17 { id: 3, name: 'Charlie' }, 18 { id: 4, name: 'Diana' } 19]; 20const userChunks = chunk(users, 2); 21console.log(userChunks); 22// [ 23// [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }], 24// [{ id: 3, name: 'Charlie' }, { id: 4, name: 'Diana' }] 25// ] 26 27// Edge cases 28console.log(chunk([], 2)); // [] 29console.log(chunk([1, 2, 3], 5)); // [[1, 2, 3]]
Flattens an array to a specified depth, converting nested arrays into a single-level array.
1import { flatten } from '@andranik-arakelyan/js-utilities'; 2 3// Flatten one level deep (default) 4const nested = [1, [2, 3], [4, [5, 6]]]; 5const result = flatten(nested); 6console.log(result); // [1, 2, 3, 4, [5, 6]] 7 8// Flatten completely (infinite depth) 9const deepNested = [1, [2, [3, [4, 5]]]]; 10const completelyFlat = flatten(deepNested, Infinity); 11console.log(completelyFlat); // [1, 2, 3, 4, 5] 12 13// Flatten to specific depth 14const mixed = [1, [2, [3, [4, 5]]]]; 15const flattenTwo = flatten(mixed, 2); 16console.log(flattenTwo); // [1, 2, 3, [4, 5]] 17 18// With objects and mixed types 19const data = [ 20 { id: 1 }, 21 [{ id: 2 }, { id: 3 }], 22 [{ id: 4 }, [{ id: 5 }]] 23]; 24const flatObjects = flatten(data); 25console.log(flatObjects); 26// [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, [{ id: 5 }]] 27 28// Processing API response data 29const apiData = [ 30 { users: [{id: 1}, {id: 2}] }, 31 { users: [{id: 3}] } 32]; 33const allUsers = flatten(apiData.map(d => d.users)); 34console.log(allUsers); // [{id: 1}, {id: 2}, {id: 3}]
Returns a new array containing elements that are present in both input arrays. Uses Set for efficient lookup, maintaining order from the first array.
1import { intersection } from '@andranik-arakelyan/js-utilities'; 2 3// Basic usage with numbers 4const arr1 = [1, 2, 3, 4]; 5const arr2 = [3, 4, 5, 6]; 6const result = intersection(arr1, arr2); 7console.log(result); // [3, 4] 8 9// With strings 10const colors1 = ['red', 'blue', 'green']; 11const colors2 = ['blue', 'yellow', 'green']; 12const common = intersection(colors1, colors2); 13console.log(common); // ['blue', 'green'] 14 15// Maintains order from the first array 16const ordered1 = [4, 1, 3, 2]; 17const ordered2 = [2, 3, 4, 1]; 18const orderedResult = intersection(ordered1, ordered2); 19console.log(orderedResult); // [4, 1, 3, 2] 20 21// Handles duplicates correctly 22const duplicates1 = [1, 2, 2, 3, 3]; 23const duplicates2 = [2, 3, 4]; 24const duplicatesResult = intersection(duplicates1, duplicates2); 25console.log(duplicatesResult); // [2, 2, 3, 3] 26 27// With objects (by reference) 28const obj1 = { id: 1 }; 29const obj2 = { id: 2 }; 30const objects1 = [obj1, obj2]; 31const objects2 = [obj1, { id: 3 }]; 32const commonObjects = intersection(objects1, objects2); 33console.log(commonObjects); // [{ id: 1 }]
Returns a new array containing elements that are in the first array but not in the second array. Uses Set for efficient lookup, maintaining order from the first array.
1import { difference } from '@andranik-arakelyan/js-utilities'; 2 3// Basic usage with numbers 4const arr1 = [1, 2, 3, 4, 5]; 5const arr2 = [3, 4]; 6const result = difference(arr1, arr2); 7console.log(result); // [1, 2, 5] 8 9// With strings 10const colors1 = ['red', 'blue', 'green', 'yellow']; 11const colors2 = ['blue', 'green']; 12const remaining = difference(colors1, colors2); 13console.log(remaining); // ['red', 'yellow'] 14 15// Maintains order from the first array 16const ordered1 = [5, 1, 3, 2, 4]; 17const ordered2 = [2, 4]; 18const orderedResult = difference(ordered1, ordered2); 19console.log(orderedResult); // [5, 1, 3] 20 21// Handles duplicates correctly 22const duplicates1 = [1, 2, 2, 3, 3, 4]; 23const duplicates2 = [2, 4]; 24const duplicatesResult = difference(duplicates1, duplicates2); 25console.log(duplicatesResult); // [1, 3, 3] 26 27// With objects (by reference) 28const obj1 = { id: 1 }; 29const obj2 = { id: 2 }; 30const obj3 = { id: 3 }; 31const objects1 = [obj1, obj2, obj3]; 32const objects2 = [obj2]; 33const filtered = difference(objects1, objects2); 34console.log(filtered); // [{ id: 1 }, { id: 3 }] 35 36// Returns empty array when all elements are excluded 37const all = [1, 2, 3]; 38const excludeAll = [1, 2, 3, 4, 5]; 39const empty = difference(all, excludeAll); 40console.log(empty); // []
Creates a deep clone of an object or array, creating a new copy of all nested objects and arrays. This function handles circular references and various JavaScript built-in types.
1import { deepClone } from '@andranik-arakelyan/js-utilities'; 2 3// Simple object cloning 4const obj = { a: 1, b: { c: 2 } }; 5const clone = deepClone(obj); 6clone.b.c = 3; 7console.log(obj.b.c); // Still 2 8 9// Handling arrays and nested structures 10const arr = [1, { x: [2, 3] }]; 11const cloneArr = deepClone(arr); 12cloneArr[1].x[0] = 10; 13console.log(arr[1].x[0]); // Still 2 14 15// Handling circular references 16const circular = { a: 1 }; 17circular.self = circular; 18const cloneCircular = deepClone(circular); 19console.log(cloneCircular.self === cloneCircular); // true 20 21// Handling built-in types 22const data = { 23 date: new Date(), 24 regex: /test/g, 25 set: new Set([1, 2, 3]), 26 map: new Map([['key', 'value']]) 27}; 28const cloneData = deepClone(data); 29console.log(cloneData.date instanceof Date); // true 30console.log(cloneData.regex instanceof RegExp); // true 31console.log(cloneData.set instanceof Set); // true 32console.log(cloneData.map instanceof Map); // true
Generates a random integer in a specified range.
1import { randomInt } from '@andranik-arakelyan/js-utilities'; 2 3// Random number between 1 and 10 4const random = randomInt(10, 1); 5console.log(random); // Example output: 7
Generates a random boolean value.
1import { randomBoolean } from '@andranik-arakelyan/js-utilities'; 2 3const random = randomBoolean(); 4console.log(random); // Either true or false
Returns information about the current code execution context.
1import { currentCodeInfo } from '@andranik-arakelyan/js-utilities'; 2 3function exampleFunction() { 4 const info = currentCodeInfo(); 5 console.log(info); 6 // Output: 7 // { 8 // className: "", 9 // methodName: "exampleFunction", 10 // filepath: "/path/to/your/file.js", 11 // filename: "file.js", 12 // lineNumber: 4, 13 // columnNumber: 15 14 // } 15} 16 17exampleFunction();
Creates a function that ensures the original function is only ever called once, regardless of how many times the returned function is called. Subsequent calls to the wrapped function return the result of the first invocation.
1import { once } from '@andranik-arakelyan/js-utilities'; 2 3// Create a function that will only execute once 4const initializeApp = once(() => { 5 console.log('App initialized!'); 6 return 'Initialization complete'; 7}); 8 9// First call - function executes 10const result1 = initializeApp(); // Logs: 'App initialized!' 11 12// Subsequent calls - function is not executed again 13const result2 = initializeApp(); // No log output 14 15// Both calls return the same result 16console.log(result1 === result2); // true 17 18// Works with parameters and preserves this context 19const obj = { 20 data: 'example', 21 process: once(function(this: { data: string }, prefix: string) { 22 console.log(`Processing ${prefix} ${this.data}`); 23 return `${prefix}-${this.data}`; 24 }) 25}; 26 27// First call with parameters 28obj.process('test'); // Logs: 'Processing test example', returns: 'test-example' 29 30// Second call - function is not executed again even with different parameters 31obj.process('another'); // No log output, still returns: 'test-example'
Creates a debounced function that delays invoking the provided function until after the specified wait time has elapsed since the last time it was invoked. The function will only execute once the wait period has elapsed with no new calls. This is particularly useful when dealing with events that fire rapidly, such as window resizing, scrolling, or keystrokes, when you want to execute the handler only after the user has stopped the action.
1import { debounce } from '@andranik-arakelyan/js-utilities'; 2 3// Create a debounced version of a function 4const handleInput = debounce((value) => { 5 // This will only execute after the user has stopped typing for 300ms 6 console.log('Processing input:', value); 7 performSearch(value); 8}, 300); 9 10// Attach to an input event 11inputElement.addEventListener('input', e => handleInput(e.target.value)); 12 13// Multiple rapid calls reset the timer each time 14handleInput('a'); // Starts the timer 15handleInput('ab'); // Cancels previous timer, starts a new one 16handleInput('abc'); // Cancels previous timer, starts a new one 17// After 300ms of no calls, the function executes with 'abc' 18 19// With proper TypeScript typing 20const calculateLayout = debounce((width: number, height: number): string => { 21 // Expensive calculation that should not run on every resize event 22 return `${width}x${height}`; 23}, 100); 24 25// Cancel a pending debounced call if needed 26handleInput.cancel();
Creates a throttled function that only invokes the provided function at most once per every specified wait milliseconds, regardless of how many times it's called. This is useful when you want to limit the rate at which a function is executed, such as during scroll events or continuous button clicks.
1import { throttle } from '@andranik-arakelyan/js-utilities'; 2 3// Create a throttled version of a function 4const handleScroll = throttle(() => { 5 // This will execute at most once every 300ms, even if scrolling continuously 6 console.log('Processing scroll event'); 7}, 300); 8 9// Attach to a scroll event 10window.addEventListener('scroll', handleScroll); 11 12// With proper TypeScript typing 13const updatePosition = throttle((x: number, y: number): string => { 14 // Update UI based on position, but not too frequently 15 return `${x},${y}`; 16}, 100); 17 18// Cancel a pending throttled call if needed 19handleScroll.cancel();
Creates a promise that resolves after a specified delay.
1import { wait } from '@andranik-arakelyan/js-utilities'; 2 3// Wait for 1 second 4await wait(1000); 5 6// Chain with other operations 7wait(500).then(() => console.log('Half a second has passed')); 8 9// Use in an async function 10async function delayedOperation() { 11 console.log('Starting'); 12 await wait(2000); 13 console.log('2 seconds have passed'); 14}
Retries an async function with configurable attempts and exponential backoff.
1import { retry } from '@andranik-arakelyan/js-utilities'; 2 3// Basic usage with default options (3 attempts) 4const data = await retry(() => fetchData()); 5 6// With custom retry configuration 7const result = await retry( 8 () => riskyOperation(), 9 { 10 attempts: 5, // Maximum attempts including initial attempt 11 delay: 1000, // Initial delay in milliseconds 12 backoffFactor: 2, // Multiply delay by this factor after each attempt 13 retryIf: (err) => err instanceof NetworkError, // Only retry specific errors 14 onRetry: (err, attempt) => console.log(`Retry attempt ${attempt}`) // Track retries 15 } 16);
Wraps an async function to handle errors gracefully without throwing exceptions. Returns a standardized result object instead of throwing errors, making error handling explicit and preventing unhandled promise rejections.
1import { safeAsync } from '@andranik-arakelyan/js-utilities'; 2 3// Basic usage with API call 4const result = await safeAsync(() => fetchUserData(userId)); 5if (result.success) { 6 console.log('User data:', result.data); 7} else { 8 console.error('Failed to fetch user:', result.error.message); 9} 10 11// With file operations that might fail 12const fileResult = await safeAsync(() => fs.readFile('config.json', 'utf8')); 13if (fileResult.success) { 14 const config = JSON.parse(fileResult.data); 15 // Process config... 16} else { 17 console.error('File read failed:', fileResult.error); 18 // Handle error gracefully... 19} 20 21// No try/catch blocks needed - errors are values 22const apiResults = await Promise.all([ 23 safeAsync(() => fetchUsers()), 24 safeAsync(() => fetchPosts()), 25 safeAsync(() => fetchComments()) 26]); 27 28apiResults.forEach((result, index) => { 29 if (result.success) { 30 console.log(`API ${index} succeeded:`, result.data); 31 } else { 32 console.log(`API ${index} failed:`, result.error.message); 33 } 34});
Contributions are welcome! Please open an issue or submit a pull request.
This project is licensed under the MIT License - see the LICENSE file for details.
No vulnerabilities found.
No security vulnerabilities found.