Package Exports
- @protorians/core
- @protorians/core/facades/appearance.d.ts
- @protorians/core/facades/appearance.js
- @protorians/core/facades/climbing.d.ts
- @protorians/core/facades/climbing.js
- @protorians/core/facades/index.d.ts
- @protorians/core/facades/index.js
- @protorians/core/facades/navigation.d.ts
- @protorians/core/facades/navigation.js
- @protorians/core/supports/appearance.d.ts
- @protorians/core/supports/appearance.js
- @protorians/core/supports/callable.d.ts
- @protorians/core/supports/callable.js
- @protorians/core/supports/capabilities.d.ts
- @protorians/core/supports/capabilities.js
- @protorians/core/supports/climbing.d.ts
- @protorians/core/supports/climbing.js
- @protorians/core/supports/collection.d.ts
- @protorians/core/supports/collection.js
- @protorians/core/supports/dictionary.d.ts
- @protorians/core/supports/dictionary.js
- @protorians/core/supports/directive.d.ts
- @protorians/core/supports/directive.js
- @protorians/core/supports/element.d.ts
- @protorians/core/supports/element.js
- @protorians/core/supports/enums.d.ts
- @protorians/core/supports/enums.js
- @protorians/core/supports/environment.d.ts
- @protorians/core/supports/environment.js
- @protorians/core/supports/event-dispatcher.d.ts
- @protorians/core/supports/event-dispatcher.js
- @protorians/core/supports/index.d.ts
- @protorians/core/supports/index.js
- @protorians/core/supports/metric.d.ts
- @protorians/core/supports/metric.js
- @protorians/core/supports/navigation.d.ts
- @protorians/core/supports/navigation.js
- @protorians/core/supports/scheme.d.ts
- @protorians/core/supports/scheme.js
- @protorians/core/supports/setter.d.ts
- @protorians/core/supports/setter.js
- @protorians/core/supports/signal.d.ts
- @protorians/core/supports/signal.js
- @protorians/core/supports/token-list.d.ts
- @protorians/core/supports/token-list.js
- @protorians/core/supports/walkable-list.d.ts
- @protorians/core/supports/walkable-list.js
- @protorians/core/types/appearance.d.ts
- @protorians/core/types/appearance.js
- @protorians/core/types/attribute.d.ts
- @protorians/core/types/attribute.js
- @protorians/core/types/capabilities.d.ts
- @protorians/core/types/capabilities.js
- @protorians/core/types/climbing.d.ts
- @protorians/core/types/climbing.js
- @protorians/core/types/collection.d.ts
- @protorians/core/types/collection.js
- @protorians/core/types/composite.d.ts
- @protorians/core/types/composite.js
- @protorians/core/types/dictionary.d.ts
- @protorians/core/types/dictionary.js
- @protorians/core/types/directive.d.ts
- @protorians/core/types/directive.js
- @protorians/core/types/element.d.ts
- @protorians/core/types/element.js
- @protorians/core/types/event.d.ts
- @protorians/core/types/event.js
- @protorians/core/types/index.d.ts
- @protorians/core/types/index.js
- @protorians/core/types/navigation.d.ts
- @protorians/core/types/navigation.js
- @protorians/core/types/object.d.ts
- @protorians/core/types/object.js
- @protorians/core/types/scheme.d.ts
- @protorians/core/types/scheme.js
- @protorians/core/types/setter.d.ts
- @protorians/core/types/setter.js
- @protorians/core/types/signals.d.ts
- @protorians/core/types/signals.js
- @protorians/core/types/token-list.d.ts
- @protorians/core/types/token-list.js
- @protorians/core/types/utilities.d.ts
- @protorians/core/types/utilities.js
- @protorians/core/types/value.d.ts
- @protorians/core/types/value.js
- @protorians/core/types/walkable.d.ts
- @protorians/core/types/walkable.js
- @protorians/core/utilities/date.d.ts
- @protorians/core/utilities/date.js
- @protorians/core/utilities/file.d.ts
- @protorians/core/utilities/file.js
- @protorians/core/utilities/function.d.ts
- @protorians/core/utilities/function.js
- @protorians/core/utilities/html.d.ts
- @protorians/core/utilities/html.js
- @protorians/core/utilities/index.d.ts
- @protorians/core/utilities/index.js
- @protorians/core/utilities/number.d.ts
- @protorians/core/utilities/number.js
- @protorians/core/utilities/object.d.ts
- @protorians/core/utilities/object.js
- @protorians/core/utilities/process.d.ts
- @protorians/core/utilities/process.js
- @protorians/core/utilities/text.d.ts
- @protorians/core/utilities/text.js
- @protorians/core/utilities/url.d.ts
- @protorians/core/utilities/url.js
Readme
@protorians/core
A powerful, flexible utility library for modern JavaScript and TypeScript applications.
Table of Contents
- Overview
- Installation
- Core Concepts
- Basic Usage
- Advanced Features
- API Reference
- Types Reference
- License
Overview
@protorians/core is a comprehensive utility library that provides a foundation for building modern JavaScript and TypeScript applications. It includes utilities for event handling, state management, data structures, and common operations on strings, numbers, objects, and more.
Installation
# Using npm
npm install @protorians/core
# Using yarn
yarn add @protorians/core
# Using pnpm
pnpm add @protorians/coreCore Concepts
Signals
Signals are a powerful event handling system that allows you to create, dispatch, and listen for events in your application. The library provides two main interfaces for signals:
- SignalStack: A stack-based event system for registering listeners and dispatching events.
- SignalController: A reactive state management system that allows you to track and respond to state changes.
import { Signal } from '@protorians/core';
// Create a signal stack
const signal = new Signal.Stack<{
click: { x: number; y: number };
hover: { element: HTMLElement };
}>();
// Listen for events
signal.listen('click', ({ x, y }) => {
console.log(`Clicked at (${x}, ${y})`);
});
// Dispatch events
signal.dispatch('click', { x: 100, y: 200 });Dictionaries
Dictionaries are key-value stores with a rich API for manipulating and accessing data. They provide type-safe access to values and methods for transforming the data.
import { Dictionary } from '@protorians/core';
// Create a dictionary
const dict = new Dictionary<{
name: string;
age: number;
email: string;
}>();
// Set values
dict.set('name', 'John Doe');
dict.set('age', 30);
dict.set('email', 'john@example.com');
// Get values
console.log(dict.get('name')); // 'John Doe'
// Convert to array
console.log(dict.array); // [['name', 'John Doe'], ['age', 30], ['email', 'john@example.com']]Collections
Collections are ordered lists of items with methods for adding, removing, and manipulating items. They provide a more powerful alternative to arrays.
import { Collection } from '@protorians/core';
// Create a collection
const collection = new Collection<string>();
// Add items
collection.add('apple');
collection.add('banana');
collection.add('orange');
// Check if an item exists
console.log(collection.has('banana')); // true
// Remove an item
collection.remove('banana');
// Iterate over items
collection.each((item, index) => {
console.log(`Item ${index}: ${item}`);
});Environment
The Environment utility provides information about the current execution environment, such as whether the code is running in a browser, Node.js, or a service worker.
import { Environment } from '@protorians/core';
if (Environment.Client) {
// Code running in a browser
console.log('Running in a browser');
} else if (Environment.Server) {
// Code running in Node.js
console.log('Running in Node.js');
}Basic Usage
import {
Signal,
Dictionary,
Collection,
Environment,
Text,
Number,
Object
} from '@protorians/core';
// Create a signal stack
const signal = new Signal.Stack<{
update: { value: number };
}>();
// Listen for events
signal.listen('update', ({ value }) => {
console.log(`Value updated to ${value}`);
});
// Create a dictionary
const dict = new Dictionary<{
count: number;
}>();
// Set initial value
dict.set('count', 0);
// Update the value and dispatch an event
function increment() {
const currentCount = dict.get('count');
dict.set('count', currentCount + 1);
signal.dispatch('update', { value: currentCount + 1 });
}
// Use text utilities
const slug = Text.slugify('Hello World!'); // 'hello-world'
const truncated = Text.truncate('This is a long text', 10); // 'This is a...'
// Use number utilities
const formatted = Number.format(1234.56, 2); // '1,234.56'
const random = Number.random(1, 100); // Random number between 1 and 100
// Use object utilities
const merged = Object.merge({ a: 1 }, { b: 2 }); // { a: 1, b: 2 }
const picked = Object.pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { a: 1, c: 3 }Advanced Features
Signal Stack
The Signal Stack provides a powerful event system with features like:
- Event Prioritization: Control the order in which listeners are called.
- Cancellable Events: Allow listeners to cancel the event propagation.
- Computed Values: Get the computed result of an event dispatch.
import { Signal } from '@protorians/core';
const signal = new Signal.Stack<{
calculate: { a: number; b: number };
}>();
// Add a listener with high priority
signal.listen('calculate', ({ a, b }) => {
return a + b;
}, { index: 0 });
// Add a listener with lower priority
signal.listen('calculate', ({ a, b }) => {
console.log(`Calculating ${a} + ${b}`);
}, { index: 1 });
// Dispatch and get the computed result
signal.dispatch('calculate', { a: 5, b: 3 });
const result = signal.computed<number>('calculate');
console.log(result); // 8Signal Controller
The Signal Controller provides reactive state management with features like:
- State Tracking: Track changes to state properties.
- Effect Callbacks: Execute callbacks when state changes.
- State Reset: Reset state to its original values.
import { Signal } from '@protorians/core';
// Create a state object
const state = {
count: 0,
name: 'John'
};
// Create a signal controller
const controller = new Signal.Controller(state);
// Add an effect callback
controller.effect(({ target, name, value }) => {
console.log(`Property ${String(name)} changed to ${value}`);
});
// Update state
controller.assign('count', 1); // Logs: Property count changed to 1
controller.assign('name', 'Jane'); // Logs: Property name changed to Jane
// Reset state
controller.reset(state);Dictionary
The Dictionary class provides advanced features for working with key-value data:
- Type Safety: Ensure type safety for keys and values.
- Data Transformation: Transform data using parsers.
- Serialization: Convert to and from strings.
import { Dictionary } from '@protorians/core';
// Create a dictionary with initial values
const dict = new Dictionary<{
name: string;
age: number;
email: string;
}>({
name: 'John Doe',
age: 30,
email: 'john@example.com'
});
// Transform values
dict.parse((key, value) => {
if (key === 'name') {
return value.toUpperCase();
}
return value;
});
console.log(dict.get('name')); // 'JOHN DOE'
// Convert to string
const str = dict.string;
console.log(str); // '{"name":"JOHN DOE","age":30,"email":"john@example.com"}'
// Create from string
const newDict = new Dictionary<{
foo: string;
bar: number;
}>();
newDict.fromString('{"foo":"hello","bar":42}');
console.log(newDict.get('foo')); // 'hello'Utilities
The library provides a rich set of utilities for common operations:
- Text: String manipulation utilities.
- Number: Number formatting and manipulation utilities.
- Object: Object manipulation utilities.
- Date: Date formatting and manipulation utilities.
- URL: URL parsing and manipulation utilities.
- HTML: HTML manipulation utilities.
import {
Text,
Number,
Object,
Date,
URL,
HTML
} from '@protorians/core';
// Text utilities
const camelCase = Text.camelCase('hello-world'); // 'helloWorld'
const kebabCase = Text.kebabCase('helloWorld'); // 'hello-world'
const capitalize = Text.capitalize('hello'); // 'Hello'
// Number utilities
const clamp = Number.clamp(150, 0, 100); // 100
const pad = Number.pad(5, 3); // '005'
const isEven = Number.isEven(4); // true
// Object utilities
const clone = Object.clone({ a: 1, b: { c: 2 } }); // Deep clone
const isEqual = Object.isEqual({ a: 1 }, { a: 1 }); // true
const omit = Object.omit({ a: 1, b: 2, c: 3 }, ['b']); // { a: 1, c: 3 }
// Date utilities
const format = Date.format(new Date(), 'YYYY-MM-DD'); // '2023-05-15'
const addDays = Date.addDays(new Date(), 5); // Date 5 days in the future
const isLeapYear = Date.isLeapYear(2024); // true
// URL utilities
const parse = URL.parse('https://example.com/path?query=value');
const buildQuery = URL.buildQuery({ a: 1, b: 'test' }); // 'a=1&b=test'
const joinPath = URL.joinPath('/base', 'path', 'to', 'resource'); // '/base/path/to/resource'
// HTML utilities
const escape = HTML.escape('<div>Hello</div>'); // '<div>Hello</div>'
const unescape = HTML.unescape('<div>Hello</div>'); // '<div>Hello</div>'
const stripTags = HTML.stripTags('<p>Hello <b>World</b></p>'); // 'Hello World'API Reference
Signals
The Signals module provides tools for event handling and state management.
Properties
Stack: Class for creating event stacksController: Class for creating reactive state controllers
Methods
Signal.Stack:
listen(type, callable, options): Adds a listener for an eventdispatch(type, payload): Dispatches an eventcomputed<T>(type): Gets the computed result of an eventremove(type, index): Removes a listener by indexremoveStack(type): Removes all listeners for an eventremoveCallable(callable, type): Removes a specific listenerclear(): Removes all listeners
Signal.Controller:
update(target): Updates the statereset(target): Resets the stateassign(key, value): Assigns a value to a state propertyeffect(callable): Adds an effect callbacktrigger(name, value): Triggers an effectcompute(): Computes the current state
Dictionary
The Dictionary class provides a type-safe key-value store.
Properties
map: Gets the underlying objectarray: Gets the dictionary as an array of key-value pairsstring: Gets the dictionary as a JSON string
Methods
get(key): Gets a value by keyset(key, value): Sets a value by keyremove(key): Removes a keyclear(): Removes all keysfromString(data): Initializes from a JSON stringparse(callable): Transforms values using a parsermany(values): Sets multiple valuesvalues(): Gets all valueskeys(): Gets all keys
Utilities
The library provides various utility modules for common operations.
Text
camelCase(str): Converts a string to camelCasekebabCase(str): Converts a string to kebab-casesnakeCase(str): Converts a string to snake_casecapitalize(str): Capitalizes the first lettertruncate(str, length, suffix): Truncates a stringslugify(str): Converts a string to a URL-friendly slugtrimSpace(str): Trims and normalizes whitespacepad(str, length, char): Pads a string to a specific length
Number
format(num, decimals, decimalSeparator, thousandsSeparator): Formats a numberrandom(min, max): Generates a random numberclamp(num, min, max): Clamps a number between min and maxpad(num, length): Pads a number with leading zerosisEven(num): Checks if a number is evenisOdd(num): Checks if a number is oddround(num, decimals): Rounds a number to a specific number of decimals
Object
clone(obj): Deep clones an objectmerge(obj1, obj2): Merges two objectspick(obj, keys): Creates a new object with selected keysomit(obj, keys): Creates a new object without specified keysisEqual(obj1, obj2): Checks if two objects are equalisEmpty(obj): Checks if an object is emptyentries(obj): Gets an array of key-value pairsfromEntries(entries): Creates an object from key-value pairs
Types Reference
| Category | Type | Description |
|---|---|---|
| Signal Types | ISignalStack<M> |
Interface for signal stacks with generic event map |
ISignalController<I> |
Interface for reactive state controllers | |
ISignalStackCallable<P> |
Type for signal stack callback functions | |
ISignalStackOptions |
Options for signal stack listeners | |
| Dictionary Types | IDictionary<T> |
Interface for dictionaries with generic value types |
IDictionaryCallbackParser<T> |
Type for dictionary value parsers | |
| Collection Types | ICollection<T> |
Interface for collections with generic item types |
ICollectionCallable<T> |
Type for collection callback functions | |
| Environment Types | IEnvironment |
Interface for environment detection |
| Utility Types | ITextUtilities |
Interface for text utilities |
INumberUtilities |
Interface for number utilities | |
IObjectUtilities |
Interface for object utilities | |
IDateUtilities |
Interface for date utilities | |
IURLUtilities |
Interface for URL utilities | |
IHTMLUtilities |
Interface for HTML utilities |
License
This project is licensed under the MIT License. See the LICENSE file for details.