OneLib.js Documentation

Complete API reference and developer guide for the modern JavaScript utility library

Introduction

OneLib.js is a minimalist JavaScript utility library designed to provide common functionality through simple, memorable one-word function names. With zero dependencies and a tiny footprint, it's perfect for rapid prototyping and production applications.

Installation

NPM

npm install @gamedevayaan/onelib

Yarn

yarn add @gamedevayaan/onelib

CDN

<script src="https://cdn.jsdelivr.net/npm/@gamedevayaan/onelib@latest/onelib.min.js"></script>

Quick Start

ES6 Modules

import OneLib from '@gamedevayaan/onelib'; // DOM manipulation OneLib.select('#myElement'); OneLib.html('#content', 'Hello World'); // Utilities OneLib.sum([1, 2, 3, 4, 5]); // 15 OneLib.slug('Hello World!'); // 'hello-world' // Storage OneLib.save('user', { name: 'John', age: 30 }); const user = OneLib.load('user');

CommonJS

const OneLib = require('@gamedevayaan/onelib'); // Same API as ES6 modules OneLib.rand(1, 100); OneLib.unique([1, 2, 2, 3]); // [1, 2, 3]

Browser Global

<script src="onelib.min.js"></script> <script> // OneLib is available globally OneLib.select('#myButton'); OneLib.on('#myButton', 'click', () => { OneLib.html('#output', 'Button clicked!'); }); </script>

DOM Utilities

Powerful DOM manipulation functions for modern web development.

select(selector)
Select the first element matching the CSS selector.
Parameters: selector (string) - CSS selector
Returns: Element | null
Example:
const button = OneLib.select('#submit-btn'); const firstCard = OneLib.select('.card');
selectall(selector)
Select all elements matching the CSS selector.
Parameters: selector (string) - CSS selector
Returns: NodeList
Example:
const allButtons = OneLib.selectall('.btn'); const menuItems = OneLib.selectall('.menu-item');
html(selector, content)
Get or set innerHTML of an element.
Parameters: selector (string|Element), content (string, optional)
Returns: String (get) | Element (set)
Example:
// Set content OneLib.html('#content', '<h1>Welcome!</h1>'); // Get content const currentContent = OneLib.html('#content');
css(selector, styles)
Apply CSS styles to an element.
Parameters: selector (string|Element), styles (object)
Returns: Element
Example:
OneLib.css('#box', { backgroundColor: 'red', fontSize: '16px', padding: '20px' });
on(selector, event, callback)
Add event listener to an element.
Parameters: selector (string|Element), event (string), callback (function)
Returns: Element
Example:
OneLib.on('#submit', 'click', (e) => { console.log('Form submitted!'); }); OneLib.on('.tab', 'click', switchTab);

Math Helpers

Essential mathematical operations and number utilities.

sum(array)
Calculate the sum of numbers in an array.
Parameters: array (Array<number>) - Array of numbers
Returns: number
Example:
const prices = [19.99, 29.99, 9.99]; const total = OneLib.sum(prices); // 59.97 const scores = [85, 92, 78, 96]; const totalScore = OneLib.sum(scores); // 351
avg(array)
Calculate the average of numbers in an array.
Parameters: array (Array<number>) - Array of numbers
Returns: number
Example:
const grades = [85, 92, 78, 96, 89]; const average = OneLib.avg(grades); // 88 const temperatures = [72, 75, 68, 71]; const avgTemp = OneLib.avg(temperatures); // 71.5
rand(min, max)
Generate a random number between min and max.
Parameters: min (number, default: 0), max (number, default: 1)
Returns: number
Example:
const randomPrice = OneLib.rand(10, 100); // 10-100 const randomPercent = OneLib.rand(0, 1); // 0-1 const diceRoll = OneLib.randint(1, 6); // 1-6 (integer)

Text Processing

Powerful text manipulation and formatting utilities.

slug(text)
Convert text to URL-friendly slug.
Parameters: text (string) - Text to convert
Returns: string
Example:
const title = "How to Build Amazing Web Apps"; const urlSlug = OneLib.slug(title); // "how-to-build-amazing-web-apps" const blogPost = "My First Blog Post!"; const url = `/posts/${OneLib.slug(blogPost)}`; // "/posts/my-first-blog-post"
truncate(text, length)
Truncate text to specified length with ellipsis.
Parameters: text (string), length (number, default: 100)
Returns: string
Example:
const longText = "This is a very long description that needs to be shortened"; const preview = OneLib.truncate(longText, 20); // "This is a very long..." const excerpt = OneLib.truncate(article.content, 150);

Array & Object Helpers

Powerful utilities for array and object manipulation.

unique(array)
Remove duplicate values from array.
Parameters: array (Array) - Input array
Returns: Array
Example:
const tags = ['javascript', 'react', 'javascript', 'vue']; const uniqueTags = OneLib.unique(tags); // ['javascript', 'react', 'vue'] const numbers = [1, 2, 2, 3, 4, 4, 5]; const uniqueNumbers = OneLib.unique(numbers); // [1, 2, 3, 4, 5]
chunk(array, size)
Split array into chunks of specified size.
Parameters: array (Array), size (number)
Returns: Array<Array>
Example:
const items = [1, 2, 3, 4, 5, 6, 7, 8]; const pages = OneLib.chunk(items, 3); // [[1, 2, 3], [4, 5, 6], [7, 8]] const users = ['Alice', 'Bob', 'Charlie', 'David']; const groups = OneLib.chunk(users, 2); // [['Alice', 'Bob'], ['Charlie', 'David']]
merge(obj1, obj2)
Merge two objects (shallow).
Parameters: obj1 (Object), obj2 (Object)
Returns: Object
Example:
const defaults = { theme: 'light', lang: 'en' }; const userPrefs = { theme: 'dark' }; const config = OneLib.merge(defaults, userPrefs); // { theme: 'dark', lang: 'en' }

Storage & Data

Local storage and data management utilities.

save(key, value)
Save data to localStorage with JSON serialization.
Parameters: key (string), value (any)
Returns: undefined
Example:
OneLib.save('user', { name: 'John', age: 30 }); OneLib.save('settings', { theme: 'dark', notifications: true }); OneLib.save('cart', [{ id: 1, price: 19.99 }]);
load(key)
Load data from localStorage with JSON parsing.
Parameters: key (string)
Returns: Any stored value or null
Example:
const user = OneLib.load('user'); // { name: 'John', age: 30 } const settings = OneLib.load('settings') || {}; // Default to empty object const cart = OneLib.load('cart') || []; // Default to empty array
copy(text)
Copy text to clipboard.
Parameters: text (string)
Returns: Promise<boolean>
Example:
// Copy share URL const success = await OneLib.copy('https://example.com/share'); if (success) { console.log('URL copied to clipboard!'); } // Copy code snippet OneLib.copy('npm install onelib');

Date Helpers

Date formatting and time utilities.

now()
Get current date object.
Parameters: None
Returns: Date
Example:
const currentTime = OneLib.now(); console.log(currentTime); // Current Date object // Use in timestamps const post = { content: 'Hello world!', createdAt: OneLib.now() };
format(date, style)
Format date according to pattern.
Parameters: date (Date|string), style (string, default: 'YYYY-MM-DD')
Returns: string
Example:
const date = new Date(); const formatted = OneLib.format(date, 'YYYY-MM-DD'); // '2024-01-15' const withTime = OneLib.format(date, 'DD/MM/YYYY HH:mm'); // '15/01/2024 14:30'
since(date)
Get human-readable time since date.
Parameters: date (Date|string)
Returns: string
Example:
const postDate = new Date('2024-01-10'); const timeAgo = OneLib.since(postDate); // '5 days ago' // Use in social media feeds const post = { content: 'Just launched my new app!', timestamp: OneLib.since(post.createdAt) };

Network Helpers

HTTP requests and network utilities.

get(url)
Make GET request and return text response.
Parameters: url (string)
Returns: Promise<string>
Example:
// Load HTML template const template = await OneLib.get('/templates/card.html'); // Load text data const csvData = await OneLib.get('/data/export.csv');
json(url)
Make GET request and return JSON response.
Parameters: url (string)
Returns: Promise<Object>
Example:
// Fetch API data const users = await OneLib.json('/api/users'); const config = await OneLib.json('/api/config'); // Use in applications users.forEach(user => { console.log(user.name); });

Animations

CSS animation and transition utilities.

fadein(selector, duration)
Fade in element with animation.
Parameters: selector (string|Element), duration (number, default: 300)
Returns: Element
Example:
// Show modal with fade effect OneLib.fadein('#modal', 500); // Show notification OneLib.fadein('.notification', 300);
move(selector, x, y)
Move element to coordinates.
Parameters: selector (string|Element), x (number), y (number)
Returns: Element
Example:
// Move element to position OneLib.move('#draggable', 100, 50); // Animate to random position const randomX = OneLib.rand(0, 200); const randomY = OneLib.rand(0, 100); OneLib.move('.floating-element', randomX, randomY);

Type Checking

Type validation and checking utilities.

isnum(val)
Check if value is a number.
Parameters: val (any)
Returns: boolean
Example:
if (OneLib.isnum(userInput)) { const result = userInput * 2; } // Validate form input const age = document.getElementById('age').value; if (!OneLib.isnum(age)) { showError('Please enter a valid number'); }
isempty(val)
Check if value is empty.
Parameters: val (any)
Returns: boolean
Example:
// Form validation if (OneLib.isempty(email)) { showError('Email is required'); } // Check arrays and objects if (!OneLib.isempty(cart)) { showCheckoutButton(); }

Utilities

General purpose utility functions.

wait(ms)
Wait for milliseconds (Promise-based).
Parameters: ms (number)
Returns: Promise<void>
Example:
// Add delay in async function async function showSequence() { OneLib.html('#step1', 'Step 1 complete'); await OneLib.wait(1000); OneLib.html('#step2', 'Step 2 complete'); await OneLib.wait(1000); OneLib.html('#step3', 'All done!'); }
debounce(func, delay)
Create debounced version of function.
Parameters: func (Function), delay (number)
Returns: Function
Example:
// Debounce search input const debouncedSearch = OneLib.debounce(searchFunction, 300); document.getElementById('search').addEventListener('input', debouncedSearch); // Debounce save function const debouncedSave = OneLib.debounce(() => { OneLib.save('draft', editor.getContent()); }, 1000);

Framework Integration

OneLib.js works seamlessly with all major JavaScript frameworks.

React

import React, { useState, useEffect } from 'react'; import OneLib from '@gamedevayaan/onelib'; function ShoppingCart() { const [items, setItems] = useState([]); const [total, setTotal] = useState(0); useEffect(() => { const savedItems = OneLib.load('cart') || []; setItems(savedItems); setTotal(OneLib.sum(savedItems)); }, []); const addItem = (price) => { const newItems = [...items, price]; setItems(newItems); setTotal(OneLib.sum(newItems)); OneLib.save('cart', newItems); }; return ( <div> <h2>Total: ${OneLib.round(total, 2)}</h2> <button onClick={() => addItem(19.99)}> Add Item </button> </div> ); }

Vue.js

<template> <div> <h2>Analytics Dashboard</h2> <p>Average: {{ average }}</p> <p>Total: {{ total }}</p> <button @click="generateData">Generate Data</button> </div> </template> <script> import OneLib from '@gamedevayaan/onelib'; export default { data() { return { data: [45, 67, 23, 89, 12], average: 0, total: 0 } }, methods: { calculateStats() { this.average = OneLib.avg(this.data); this.total = OneLib.sum(this.data); }, generateData() { this.data = Array.from({length: 10}, () => OneLib.randint(10, 100) ); this.calculateStats(); } }, mounted() { this.calculateStats(); } } </script>

Angular

import { Component, Injectable } from '@angular/core'; import OneLib from '@gamedevayaan/onelib'; @Injectable({ providedIn: 'root' }) export class DataService { processUserData(userData: any) { return { name: OneLib.capitalize(OneLib.trim(userData.name)), email: OneLib.lower(OneLib.trim(userData.email)), slug: OneLib.slug(userData.name), id: OneLib.uuid() }; } saveUserPreferences(prefs: any) { OneLib.save('userPrefs', prefs); } loadUserPreferences() { return OneLib.load('userPrefs') || {}; } } @Component({ selector: 'app-user-profile', template: ` <div> <h2>User Profile</h2> <p>Welcome, {{ processedUser.name }}!</p> <p>Profile URL: /users/{{ processedUser.slug }}</p> </div> ` }) export class UserProfileComponent { processedUser: any; constructor(private dataService: DataService) { const rawUser = { name: ' john doe ', email: ' JOHN@EXAMPLE.COM ' }; this.processedUser = this.dataService.processUserData(rawUser); } }

Real-World Examples

Practical examples showing OneLib.js in action for common development scenarios.

E-commerce Shopping Cart
class ShoppingCart { constructor() { this.items = OneLib.load('cart') || []; this.updateDisplay(); } addItem(product) { this.items.push({ id: OneLib.uuid(), name: product.name, price: product.price, quantity: 1 }); this.saveAndUpdate(); } calculateTotal() { const prices = this.items.map(item => item.price * item.quantity); return OneLib.round(OneLib.sum(prices), 2); } getItemCount() { return this.items.length; } saveAndUpdate() { OneLib.save('cart', this.items); this.updateDisplay(); } updateDisplay() { OneLib.html('#cart-count', this.getItemCount()); OneLib.html('#cart-total', `$${this.calculateTotal()}`); } clearCart() { this.items = []; OneLib.save('cart', []); this.updateDisplay(); } } // Usage const cart = new ShoppingCart(); cart.addItem({ name: 'Laptop', price: 999.99 }); cart.addItem({ name: 'Mouse', price: 29.99 });
Content Management System
class BlogManager { constructor() { this.posts = OneLib.load('blog-posts') || []; } createPost(title, content, author) { const post = { id: OneLib.uuid(), title: OneLib.trim(title), slug: OneLib.slug(title), content: content, author: OneLib.capitalize(OneLib.trim(author)), excerpt: OneLib.truncate(content, 150), wordCount: OneLib.words(content).length, createdAt: OneLib.now(), updatedAt: OneLib.now() }; this.posts.push(post); this.savePosts(); return post; } getPostBySlug(slug) { return this.posts.find(post => post.slug === slug); } searchPosts(query) { const searchTerm = OneLib.lower(OneLib.trim(query)); return this.posts.filter(post => OneLib.lower(post.title).includes(searchTerm) || OneLib.lower(post.content).includes(searchTerm) ); } getPostStats() { const wordCounts = this.posts.map(post => post.wordCount); return { totalPosts: this.posts.length, averageWords: OneLib.round(OneLib.avg(wordCounts), 0), totalWords: OneLib.sum(wordCounts), longestPost: OneLib.max(wordCounts), shortestPost: OneLib.min(wordCounts) }; } savePosts() { OneLib.save('blog-posts', this.posts); } } // Usage const blog = new BlogManager(); const newPost = blog.createPost( 'Getting Started with OneLib.js', 'OneLib.js is a powerful utility library...', 'john doe' ); console.log(`Post URL: /blog/${newPost.slug}`); console.log(`Word count: ${newPost.wordCount}`);
Form Validation & Processing
class FormValidator { constructor(formSelector) { this.form = OneLib.select(formSelector); this.errors = {}; this.setupValidation(); } setupValidation() { OneLib.on(this.form, 'submit', (e) => { e.preventDefault(); if (this.validateForm()) { this.submitForm(); } }); } validateForm() { this.errors = {}; // Email validation const email = OneLib.trim(OneLib.lower( OneLib.select('#email').value )); if (OneLib.isempty(email)) { this.errors.email = 'Email is required'; } else if (!email.includes('@')) { this.errors.email = 'Invalid email format'; } // Name validation const name = OneLib.trim(OneLib.select('#name').value); if (OneLib.isempty(name)) { this.errors.name = 'Name is required'; } else if (OneLib.words(name).length < 2) { this.errors.name = 'Please enter first and last name'; } // Password validation const password = OneLib.select('#password').value; if (OneLib.isempty(password)) { this.errors.password = 'Password is required'; } else if (password.length < 8) { this.errors.password = 'Password must be at least 8 characters'; } this.displayErrors(); return Object.keys(this.errors).length === 0; } displayErrors() { // Clear previous errors OneLib.selectall('.error').forEach(el => el.remove()); // Display new errors Object.keys(this.errors).forEach(field => { const input = OneLib.select(`#${field}`); const errorDiv = OneLib.create('div'); errorDiv.className = 'error'; errorDiv.textContent = this.errors[field]; input.parentNode.appendChild(errorDiv); }); } submitForm() { const formData = { id: OneLib.uuid(), name: OneLib.capitalize(OneLib.trim( OneLib.select('#name').value )), email: OneLib.lower(OneLib.trim( OneLib.select('#email').value )), submittedAt: OneLib.timestamp() }; // Save to localStorage OneLib.save('form-submission', formData); // Show success message OneLib.html('#success', 'Form submitted successfully!'); OneLib.show('#success'); // Reset form this.form.reset(); } } // Usage const validator = new FormValidator('#contact-form');

Browser Support

OneLib.js works across all modern browsers and JavaScript environments.

Desktop Browsers

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

Mobile Browsers

  • iOS Safari 12+
  • Chrome Mobile 60+
  • Firefox Mobile 55+
  • Samsung Internet 8+

JavaScript Runtimes

  • Node.js 12+
  • Deno 1.0+
  • Bun 0.1+
  • Electron 8+

All Functions Reference

Complete reference of all 63+ functions available in OneLib.js, organized by category with copy-to-clipboard functionality.

DOM Utilities (13 functions)

select(selector)

Select the first element matching the CSS selector

// Select element by ID
const element = OneLib.select('#myButton');

// Select by class
const item = OneLib.select('.menu-item');

html(selector, content)

Get or set innerHTML of elements

// Get HTML content
const content = OneLib.html('#container');

// Set HTML content
OneLib.html('#output', '

Hello World

');

css(selector, styles)

Apply CSS styles to elements

// Apply single style
OneLib.css('#box', {color: 'red'});

// Apply multiple styles
OneLib.css('.card', {
  backgroundColor: '#333',
  padding: '20px',
  borderRadius: '8px'
});

on(selector, event, callback)

Add event listeners to elements

// Add click listener
OneLib.on('#button', 'click', () => {
  console.log('Button clicked!');
});

// Add multiple event listeners
OneLib.on('.input', 'focus', handleFocus);

Math Helpers (10 functions)

sum(array)

Calculate the sum of numbers in an array

const numbers = [1, 2, 3, 4, 5];
const total = OneLib.sum(numbers); // 15

// Works with decimals
const prices = [19.99, 29.99, 9.99];
const cartTotal = OneLib.sum(prices); // 59.97

avg(array)

Calculate the average of numbers in an array

const scores = [85, 92, 78, 96, 88];
const average = OneLib.avg(scores); // 87.8

// Grade calculation
const grades = [95, 87, 92, 89];
const finalGrade = OneLib.avg(grades); // 90.75

rand(min, max)

Generate random number between min and max

// Random integer 1-10
const dice = OneLib.rand(1, 6);

// Random decimal 0-1
const probability = OneLib.rand(0, 1);

// Random price
const price = OneLib.rand(10, 100);

Text Processing (8 functions)

slug(text)

Convert text to URL-friendly slug

const title = "How to Build Amazing Web Apps";
const url = OneLib.slug(title);
// Result: "how-to-build-amazing-web-apps"

const blogPost = "10 Tips & Tricks for JavaScript!";
const slug = OneLib.slug(blogPost);
// Result: "10-tips-tricks-for-javascript"

truncate(text, length)

Truncate text with ellipsis

const longText = "This is a very long description that needs to be shortened";
const preview = OneLib.truncate(longText, 30);
// Result: "This is a very long descrip..."

// Card descriptions
const description = OneLib.truncate(article.content, 150);

Performance

OneLib.js is optimized for performance and minimal bundle impact.

Bundle Size

12KB minified
4KB gzipped

Tree Shaking

Import only what you need
Reduce bundle size further

Zero Dependencies

No external libraries
No dependency conflicts

Optimized Algorithms

Efficient implementations
Fast execution times

Tree Shaking Example

// Import only specific functions import { sum, avg, slug } from 'onelib'; // Webpack will only include these functions in your bundle const total = sum([1, 2, 3, 4, 5]); const average = avg([1, 2, 3, 4, 5]); const urlSlug = slug('My Blog Post');