Utils Support
A lightweight, zero-dependency utility library for JavaScript and TypeScript
Utils Support is a comprehensive collection of utility functions designed to make JavaScript and TypeScript development easier and more efficient. With zero dependencies and a tiny footprint, it provides a wide range of helper functions for working with arrays, objects, dates, strings, web functionality, and more.
Dual Format Support
Works with both ESM and CommonJS, making it compatible with any JavaScript or TypeScript project.
Tree-Shakable
Import only what you need, reducing bundle size and improving performance.
Type-Safe
Full TypeScript support with detailed type definitions for a better development experience.
Modular
Organized into logical categories, making it easy to find and use the functions you need.
Lightweight
Zero dependencies and a tiny footprint, keeping your project lean and efficient.
Intuitive API
Simple and consistent function naming, making the library easy to learn and use.
Installation
Install Utils Support using your favorite package manager.
npm install utils-support
yarn add utils-support
pnpm add utils-support
After installation, you can import the library in your project and start using its functions.
Usage
Utils Support supports both ESM and CommonJS imports, allowing you to use it in any JavaScript or TypeScript project.
With ESM (ES Modules)
// Import everything
import * as utils from 'utils-support';
// Import specific namespace
import { array, string } from 'utils-support';
// Import specific functions (tree-shaking friendly)
import { unique, shuffle } from 'utils-support/array';
import { formatDate } from 'utils-support/date';
With CommonJS
// Import everything
const utils = require('utils-support');
// Import specific namespace
const { array, string } = require('utils-support');
// Import specific modules
const arrayUtils = require('utils-support/array');
const dateUtils = require('utils-support/date');
TypeScript Usage
Tiny Utils comes with full TypeScript support. All functions are properly typed, providing excellent IDE autocompletion and type checking.
import { sortBy } from 'utils-support/array';
interface User {
id: number;
name: string;
age: number;
}
const users: User[] = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Alice', age: 25 },
{ id: 3, name: 'Bob', age: 40 }
];
// TypeScript knows that sortedUsers is User[]
const sortedUsers = sortBy(users, 'age');
console.log(sortedUsers);
Features
Tiny Utils provides a comprehensive set of utility functions organized into logical categories.
Key Benefits
- Comprehensive: Over 80 utility functions covering common programming tasks
- Consistent API: All functions follow the same naming and parameter conventions
- Well Documented: Detailed documentation with examples for every function
- Tested: Thoroughly tested to ensure reliability and correctness
- Modern: Built with modern JavaScript features and best practices
- Flexible: Use only what you need, when you need it
Array Utilities
Functions for manipulating and transforming arrays. These utilities help you work with arrays more efficiently, handling common tasks like filtering, sorting, grouping, and transforming array data.
Splits an array into chunks of specified size
Returns a new array with duplicate values removed
Returns a new array with elements randomly reordered
Returns values from the first array that are not in the second array
Groups array elements by a key returned by the iteratee function
Returns an array of values that are in both arrays
Flattens an array a single level deep
Gets the first element of an array
Gets the last element of an array
Creates an object composed of keys generated from the results of running each element through iteratee
Sorts an array of objects by a property or function
Counts occurrences of each value in an array
Partitions elements into two groups according to a predicate
Samples a single random element from an array
chunk
chunk(array, size)Splits an array into chunks of specified size. This is useful when you need to process arrays in smaller batches or display data in a grid layout.
| Parameter | Type | Description |
|---|---|---|
| array | T[] | The array to chunk |
| size | number | The size of each chunk |
Example
import { chunk } from 'utils-support/array';
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunk(numbers, 3);
Output
Real-world Example: Pagination
import { chunk } from 'utils-support/array';
// Simulating a list of items to paginate
const allItems = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// ... more items
{ id: 20, name: 'Item 20' }
];
// Split into pages of 5 items each
const itemsByPage = chunk(allItems, 5);
// Get items for page 2 (0-indexed)
const page2Items = itemsByPage[1];
console.log(page2Items); // Items 6-10
unique
unique(array)Returns a new array with duplicate values removed. This is useful for filtering out duplicate entries from a list.
| Parameter | Type | Description |
|---|---|---|
| array | T[] | The array to process |
Example
import { unique } from 'utils-support/array';
const withDuplicates = [1, 2, 2, 3, 4, 4, 5];
const uniqueValues = unique(withDuplicates);
Output
Real-world Example: Filtering Tags
import { unique } from 'utils-support/array';
// A list of blog posts with tags
const posts = [
{ id: 1, title: 'Post 1', tags: ['javascript', 'react', 'tutorial'] },
{ id: 2, title: 'Post 2', tags: ['javascript', 'node', 'api'] },
{ id: 3, title: 'Post 3', tags: ['react', 'tutorial', 'hooks'] }
];
// Extract all tags and remove duplicates
const allTags = unique(posts.flatMap(post => post.tags));
console.log(allTags); // ['javascript', 'react', 'tutorial', 'node', 'api', 'hooks']
Object Utilities
Functions for working with objects efficiently. These utilities help you manipulate, transform, and analyze JavaScript objects with ease.
Creates an object with only the specified keys
Creates an object without the specified keys
Deeply merges two objects
Checks if a value is an object
Creates a deep clone of an object
Flattens a nested object structure
Checks if an object is empty
Maps values in an object
Converts an object to [key, value] pairs
Converts an array of [key, value] pairs to an object
Performs a deep equality check between two objects
pick
pick(obj, keys)Creates an object with only the specified keys. This is useful for extracting a subset of properties from an object, such as creating a public version of a user object without sensitive information.
| Parameter | Type | Description |
|---|---|---|
| obj | T | The source object |
| keys | K[] | Array of keys to pick |
Example
import { pick } from 'utils-support/object';
const user = {
id: 1,
name: 'John',
email: 'john@example.com',
password: 'secret'
};
const publicUser = pick(user, ['id', 'name']);
Output
Real-world Example: API Response Filtering
import { pick } from 'utils-support/object';
// Function to handle user data from an API
function processUserData(userData) {
// Only keep the fields we need for our application
return pick(userData, ['id', 'name', 'email', 'role', 'lastLogin']);
}
// Example API response with many fields
const apiResponse = {
id: 123,
name: 'Jane Smith',
email: 'jane@example.com',
password: 'hashed_password',
role: 'admin',
lastLogin: '2023-01-15T14:30:45Z',
createdAt: '2022-05-10T09:20:30Z',
updatedAt: '2023-01-15T14:30:45Z',
securityQuestions: [...],
preferences: {...},
// ... many more fields
};
const processedUser = processUserData(apiResponse);
console.log(processedUser);
// { id: 123, name: 'Jane Smith', email: 'jane@example.com', role: 'admin', lastLogin: '2023-01-15T14:30:45Z' }
Examples
Here are some real-world examples of how to use Tiny Utils in your projects.
Data Processing
import { groupBy, sortBy } from 'utils-support/array';
import { formatDate } from 'utils-support/date';
// Sample data
const sales = [
{ id: 1, product: 'Laptop', category: 'Electronics', price: 1200, date: new Date('2023-01-15') },
{ id: 2, product: 'Headphones', category: 'Electronics', price: 100, date: new Date('2023-01-20') },
{ id: 3, product: 'Book', category: 'Books', price: 20, date: new Date('2023-01-10') },
{ id: 4, product: 'Smartphone', category: 'Electronics', price: 800, date: new Date('2023-01-05') },
{ id: 5, product: 'Desk Chair', category: 'Furniture', price: 250, date: new Date('2023-01-25') }
];
// Group sales by category
const salesByCategory = groupBy(sales, item => item.category);
console.log(salesByCategory);
/*
{
"Electronics": [
{ id: 1, product: 'Laptop', category: 'Electronics', price: 1200, date: [Date] },
{ id: 2, product: 'Headphones', category: 'Electronics', price: 100, date: [Date] },
{ id: 4, product: 'Smartphone', category: 'Electronics', price: 800, date: [Date] }
],
"Books": [
{ id: 3, product: 'Book', category: 'Books', price: 20, date: [Date] }
],
"Furniture": [
{ id: 5, product: 'Desk Chair', category: 'Furniture', price: 250, date: [Date] }
]
}
*/
// Sort sales by date
const sortedSales = sortBy(sales, 'date');
console.log(sortedSales.map(sale => ({
...sale,
date: formatDate(sale.date, 'YYYY-MM-DD')
})));
/*
[
{ id: 4, product: 'Smartphone', category: 'Electronics', price: 800, date: '2023-01-05' },
{ id: 3, product: 'Book', category: 'Books', price: 20, date: '2023-01-10' },
{ id: 1, product: 'Laptop', category: 'Electronics', price: 1200, date: '2023-01-15' },
{ id: 2, product: 'Headphones', category: 'Electronics', price: 100, date: '2023-01-20' },
{ id: 5, product: 'Desk Chair', category: 'Furniture', price: 250, date: '2023-01-25' }
]
*/
Form Validation
import { isEmail, isUrl, isEmpty, hasLengthBetween } from 'utils-support/validation';
function validateForm(formData) {
const errors = {};
// Check if name is provided and has correct length
if (isEmpty(formData.name)) {
errors.name = 'Name is required';
} else if (!hasLengthBetween(formData.name, 2, 50)) {
errors.name = 'Name must be between 2 and 50 characters';
}
// Validate email
if (isEmpty(formData.email)) {
errors.email = 'Email is required';
} else if (!isEmail(formData.email)) {
errors.email = 'Please enter a valid email address';
}
// Validate website if provided
if (formData.website && !isUrl(formData.website)) {
errors.website = 'Please enter a valid URL';
}
return {
isValid: Object.keys(errors).length === 0,
errors
};
}
// Example usage
const formData = {
name: 'Jo',
email: 'not-an-email',
website: 'example'
};
const validation = validateForm(formData);
console.log(validation);
/*
{
isValid: false,
errors: {
name: 'Name must be between 2 and 50 characters',
email: 'Please enter a valid email address',
website: 'Please enter a valid URL'
}
}
*/
Working with Local Storage
import { createNamespacedStorage } from 'utils-support/storage';
// Create a namespaced storage for user preferences
const prefsStorage = createNamespacedStorage('user-prefs');
// Save user preferences
function savePreferences(preferences) {
prefsStorage.set('theme', preferences.theme);
prefsStorage.set('fontSize', preferences.fontSize);
prefsStorage.set('notifications', preferences.notifications);
}
// Load user preferences
function loadPreferences() {
return {
theme: prefsStorage.get('theme', 'light'),
fontSize: prefsStorage.get('fontSize', 'medium'),
notifications: prefsStorage.get('notifications', true)
};
}
// Example usage
savePreferences({
theme: 'dark',
fontSize: 'large',
notifications: false
});
const userPrefs = loadPreferences();
console.log(userPrefs);
// { theme: 'dark', fontSize: 'large', notifications: false }
Frequently Asked Questions
Common questions about Tiny Utils and their answers.
What makes Tiny Utils different from other utility libraries?
Tiny Utils is designed to be lightweight, modular, and tree-shakable. Unlike larger utility libraries, it focuses on providing only the most essential functions with zero dependencies. It also offers full TypeScript support and dual ESM/CommonJS compatibility, making it suitable for any modern JavaScript project.
Can I use Tiny Utils with React, Vue, or other frameworks?
Yes, Tiny Utils is framework-agnostic and can be used with any JavaScript framework or library. It provides pure utility functions that work with standard JavaScript data structures, making it compatible with React, Vue, Angular, Svelte, or any other framework.
How does tree-shaking work with Tiny Utils?
Tiny Utils is designed with tree-shaking in mind. When you import specific functions (e.g., import { unique } from 'utils-support/array'), modern bundlers like webpack, Rollup, or esbuild will only include the code for those specific functions in your final bundle, reducing the overall size.
Is Tiny Utils suitable for production use?
Yes, Tiny Utils is thoroughly tested and designed for production use. It follows best practices for performance, security, and reliability. The library is also actively maintained and updated to ensure compatibility with the latest JavaScript features and environments.
How can I contribute to Tiny Utils?
Contributions are welcome! You can contribute by submitting bug reports, feature requests, or pull requests on the GitHub repository. Please see the Contributing section for more details.
Changelog
Track the changes and updates to Tiny Utils.
v0.1.0
January 15, 2023
- Initial release with core utility functions
- Added array, object, string, date, and web modules
- Added logger, validation, and storage modules
- Full TypeScript support
- Dual ESM/CommonJS compatibility
- Comprehensive documentation
Contributing
Contributions are welcome! Feel free to open issues and pull requests.
How to Contribute
- Fork the repository
- Create your feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add some amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Development Setup
# Clone your fork
git clone https://github.com/KazeDevID/utils-support.git
cd utils-support
# Install dependencies
npm install
# Run tests
npm test
# Build the library
npm run build
Code Style
We use ESLint and Prettier to maintain code quality and consistency. Please make sure your code passes the linting checks before submitting a pull request.
# Run linting
npm run lint
# Format code
npm run format
License
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2025 Utils Support
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.