DEV Community

Ayat Saadat
Ayat Saadat

Posted on

ayat saadati — Complete Guide

Saadati.js Toolkit: Essential JavaScript Utilities

Welcome to the Saadati.js Toolkit documentation! This isn't just another utility library; it's a carefully curated collection of practical, modern JavaScript functions designed to streamline your daily development tasks. Born out of countless hours spent crafting solutions for real-world problems, this toolkit embodies the philosophy of clean, efficient, and developer-friendly code.

You know how it is – you're building an application, and you keep writing the same helper functions over and over. Formatting dates, slugifying strings, safely accessing nested object properties... it adds up. Saadati.js is my answer to that repetitive strain. It's built to be lightweight, tree-shakable, and a joy to use.

Table of Contents

  1. Introduction
  2. Features at a Glance
  3. Installation
  4. Usage
  5. API Reference
  6. Examples
  7. FAQ
  8. Troubleshooting
  9. Contributing
  10. About the Author
  11. License

Introduction

The Saadati.js Toolkit is a minimalist yet powerful library providing common utility functions that you often find yourself writing from scratch. My goal was to create something that feels native to modern JavaScript development, focusing on immutability, pure functions, and sensible defaults. Whether you're working on a frontend app with React/Vue/Angular or a backend service with Node.js, these utilities are designed to fit seamlessly into your workflow.

I've always believed that a good tool should get out of your way and just work. That's the core principle behind Saadati.js. No bloat, no complex configurations – just solid, well-tested functions for common programming patterns.

Features at a Glance

  • Date & Time Formatting: Intuitive functions to format dates, calculate time differences, and parse various date inputs.
  • String Manipulation: Helpers for common string tasks like slugification, truncation, capitalization, and more.
  • Object & Array Helpers: Utilities for deep merging, safe property access, unique array elements, and other data transformations.
  • Validation Utilities: Simple, robust functions for common data validations (email, URL, numbers, etc.).
  • Tree-shakable: Import only what you need, keeping your bundle size minimal.
  • TypeScript Support: Fully typed for a smoother development experience.
  • No External Dependencies: Zero dependencies, ensuring a lean footprint.

Installation

Getting Saadati.js into your project is straightforward. You can install it via npm or yarn.

Using npm:

npm install saadati-js-toolkit
Enter fullscreen mode Exit fullscreen mode

Using yarn:

yarn add saadati-js-toolkit
Enter fullscreen mode Exit fullscreen mode

For those who prefer a CDN, you can also link directly to the UMD build, though this is generally less recommended for modern module-based projects:

<!-- Not recommended for production SPAs, but useful for quick prototyping -->
<script src="https://unpkg.com/saadati-js-toolkit/dist/saadati.umd.min.js"></script>
<script>
  // Access functions via SaadatiGlobal object
  console.log(SaadatiGlobal.formatDate(new Date()));
</script>
Enter fullscreen mode Exit fullscreen mode

Usage

Saadati.js is designed to be highly modular. You should import specific functions as needed to leverage tree-shaking and keep your bundle size optimal.

import { formatDate, slugify, getDeepValue } from 'saadati-js-toolkit';

// ... your code
Enter fullscreen mode Exit fullscreen mode

Let's dive into some common usage patterns.

Date & Time Utilities

Working with dates can be notoriously tricky in JavaScript. I've tried to make it a little less painful.

import { formatDate, timeAgo } from 'saadati-js-toolkit';

const now = new Date();
const yesterday = new Date(now.getTime() - (24 * 60 * 60 * 1000));
const customDate = '2023-10-27T10:00:00Z';

console.log(formatDate(now, 'YYYY-MM-DD HH:mm:ss')); // "2023-10-28 15:30:00" (example output)
console.log(formatDate(customDate, 'DD/MM/YYYY')); // "27/10/2023"
console.log(timeAgo(yesterday)); // "1 day ago"
console.log(timeAgo(new Date(now.getTime() - (5 * 60 * 1000)))); // "5 minutes ago"
Enter fullscreen mode Exit fullscreen mode

String Manipulation

From user-friendly URLs to clean display text, string operations are a constant.

import { slugify, truncate, capitalizeWords } from 'saadati-js-toolkit';

const title = "My Awesome Blog Post Title with Special Characters!";
const longText = "This is a very long text that needs to be truncated for display purposes.";

console.log(slugify(title)); // "my-awesome-blog-post-title-with-special-characters"
console.log(truncate(longText, 30)); // "This is a very long text that..."
console.log(capitalizeWords("hello world from saadati")); // "Hello World From Saadati"
Enter fullscreen mode Exit fullscreen mode

Object & Array Helpers

Navigating complex data structures is a breeze with these helpers.

import { getDeepValue, uniqueArray, deepMerge } from 'saadati-js-toolkit';

const user = {
  id: 1,
  profile: {
    name: 'John Doe',
    address: {
      city: 'New York',
      zip: '10001'
    }
  },
  settings: null
};

console.log(getDeepValue(user, 'profile.address.city')); // "New York"
console.log(getDeepValue(user, 'profile.email', 'N/A')); // "N/A"
console.log(getDeepValue(user, 'settings.theme', 'light')); // "light"

const numbers = [1, 2, 2, 3, 4, 4, 5];
console.log(uniqueArray(numbers)); // [1, 2, 3, 4, 5]

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
console.log(deepMerge(obj1, obj2));
// { a: 1, b: { c: 2, d: 3 }, e: 4 }
Enter fullscreen mode Exit fullscreen mode

Validation Utilities

Don't reinvent the wheel for basic validations.

import { isValidEmail, isValidURL, isNumeric } from 'saadati-js-toolkit';

console.log(isValidEmail('test@example.com')); // true
console.log(isValidEmail('invalid-email')); // false

console.log(isValidURL('https://dev.to/ayat_saadat')); // true
console.log(isValidURL('not-a-url')); // false

console.log(isNumeric('123')); // true
console.log(isNumeric('123a')); // false
Enter fullscreen mode Exit fullscreen mode

API Reference

Here's a detailed look at the functions available in the Saadati.js Toolkit.

Date Functions

Function Description Parameters Returns Example
formatDate Formats a date object or string into a specified string format. `date: Date string, format: string` string
timeAgo Returns a human-readable string indicating time passed since. `date: Date string` string
isSameDay Checks if two dates fall on the same calendar day. `date1: Date string, date2: Date string`

String Functions

Function Description Parameters Returns Example
slugify Converts a string into a URL-friendly slug. text: string string slugify('Hello World!') ("hello-world")
truncate Truncates a string to a specified length, adding ellipsis. text: string, length: number string truncate('Too long text', 10) ("Too long...")
capitalize Capitalizes the first letter of a string. text: string string capitalize('hello') ("Hello")
capitalizeWords Capitalizes the first letter of each word in a string. text: string string capitalizeWords('hello world') ("Hello World")
stripHtml Removes HTML tags from a string. htmlString: string string stripHtml('<p>Hello</p>') ("Hello")

Object/Array Functions

Function Description Parameters Returns Example
getDeepValue Safely retrieves a nested property from an object, with an optional default. obj: object, path: string, defaultValue?: any any getDeepValue({a:{b:1}}, 'a.b') (1)
uniqueArray Returns a new array with only unique values. arr: Array<any> Array uniqueArray([1, 2, 2, 3]) ([1, 2, 3])
deepMerge Deeply merges two or more objects. ...objects: object[] object deepMerge({a:1},{b:{c:2}}) ({a:1, b:{c:2}})
omit Creates a new object by omitting specified keys. obj: object, keys: string[] object omit({a:1, b:2, c:3}, ['b']) ({a:1, c:3})
pick Creates a new object by picking specified keys. obj: object, keys: string[] object pick({a:1, b:2, c:3}, ['a', 'c']) ({a:1, c:3})

Validation Functions

Function Description Parameters Returns Example
isValidEmail Checks if a string is a valid email address format. email: string boolean isValidEmail('test@example.com') (true)
isValidURL Checks if a string is a valid URL format. url: string boolean isValidURL('https://example.com') (true)
isNumeric Checks if a string or number represents a valid number. value: any boolean isNumeric('123') (true)
isAlphaNumeric Checks if a string contains only letters and numbers. value: string boolean isAlphaNumeric('test123') (true)

Examples

You can find more detailed examples and use cases within the examples/ directory in the project repository. Here’s a quick taste:

Scenario: Displaying User Activity Feed


javascript
import { timeAgo, truncate } from 'saadati-js-toolkit';

const activities = [
  { id: 1, user: 'Alice', action: 'posted a new article: "My Adventures in JavaScript"', timestamp: new Date(Date.now() - 3600000) },
  { id: 2, user: 'Bob', action: 'commented on "React Hooks Explained"', timestamp: new Date(Date.now() - 10 * 60 * 1000) },
  { id: 3, user: 'Charlie', action: 'liked your post', timestamp: new Date(Date.now() - 30 * 1000) },
];

activities.forEach(activity => {
  const formattedTime = timeAgo(activity.timestamp);
  const truncatedAction = truncate(activity.action, 50);
  console.log(`${activity.user} ${truncatedAction} (${formattedTime})`);
});

// Expected Output:
// Alice posted a new article: "My Adventures in JavaScrip... (1 hour ago)
// Bob commented on "React Hooks Explained" (10 minutes ago)
// Charlie liked your post (3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)