Skip to content

Commit

Permalink
docs: enhance README documentation across packages
Browse files Browse the repository at this point in the history
✨ Add detailed features sections with emojis
📚 Improve API documentation and examples
🔧 Reorganize section headers with emoji indicators
📝 Add more comprehensive usage examples
🎨 Improve formatting and readability
🏷️ Add consistent section headers across packages
  • Loading branch information
illuxiza committed Jan 30, 2025
1 parent 93be9c0 commit bcb9b29
Show file tree
Hide file tree
Showing 10 changed files with 283 additions and 200 deletions.
31 changes: 16 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
# Rustable

A TypeScript library that brings Rust's powerful features and patterns to TypeScript development. Rustable provides type-safe implementations of Rust's most valuable patterns while maintaining TypeScript's ease of use.
🦀 A TypeScript library that brings Rust's powerful features and patterns to TypeScript development. Rustable provides type-safe implementations of Rust's most valuable patterns while maintaining TypeScript's ease of use.

## Installation
## ✨ Features

- 🎯 **Trait System** - Complete Rust-like trait system
- 🔒 **Type Safety** - Comprehensive type-safe implementations
- 🎭 **Error Handling** - Pattern matching and error handling
- 🧩 **Collections** - Efficient collections and traits
- 🔁 **Iterators** - Rich iterator utilities and adapters
- 📦 **Zero Deps** - No external runtime dependencies

## 📦 Installation

```bash
npm install rustable
Expand All @@ -12,28 +21,20 @@ yarn add rustable
pnpm add rustable
```

## Features

- 🎯 Complete Rust-like trait system
- 🔒 Type-safe implementations
- 🎭 Pattern matching and error handling
- 🧩 Efficient collections and traits
- 🔁 Iterator utilities
- 📦 Zero dependencies

## Packages
## 📚 Packages

### [@rustable/commons](https://github.com/illuxiza/ts-rustable/tree/main/packages/commons#readme)

🧩 Type-safe collections and common traits

- HashMap with efficient key-value storage
- Entry API for safe map manipulation
- HashSet for unique value storage
- Vec with Rust-like operations
- IdxVec with array-like index access
- Clone trait for deep cloning
- Eq trait for equality comparison
- From trait for type conversion
- Entry API for safe map manipulation

### [@rustable/enum](https://github.com/illuxiza/ts-rustable/tree/main/packages/enum#readme)

Expand Down Expand Up @@ -85,10 +86,10 @@ pnpm add rustable
- Pointer management (Ptr) for mutable references
- Value management (Val) for immutable references

## Contributing
## 🤝 Contributing

We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

## License
## 📄 License

MIT © illuxiza
94 changes: 61 additions & 33 deletions packages/commons/README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
# @rustable/commons

A TypeScript implementation of Rust-like traits and collections, providing efficient and type-safe implementations along with common trait patterns.
🧩 A TypeScript implementation of Rust-like traits and collections, providing efficient and type-safe implementations along with common trait patterns.

## Features
## Features

- 🧰 Decorator-based trait system
- 🔒 Type-safe implementations
- 🦀 Rust-like APIs
- 🔄 Option-based value handling
- ⚡ Efficient hash-based collections
- 🎨 Default trait implementations
- 🏷️ Trait metadata
- 📦 Zero dependencies
- 🔍 Type-safe entry API for maps
- 🗃️ **HashMap** - Efficient key-value storage with hash-based lookup
- 🔍 **Entry** - Safe map manipulation with Entry API
- 📦 **HashSet** - Unique value storage with O(1) lookup
- 📚 **Vec** - Dynamic array with Rust-like operations
- 📇 **IdxVec** - Array-like collection with index access
- 🔄 **Clone** - Deep cloning support via Clone trait
- 🎯 **Eq** - Value equality comparison via Eq trait
- 🔄 **From** - Type conversion via From trait

## Installation
## 📦 Installation

```bash
npm install @rustable/commons
Expand All @@ -24,7 +23,7 @@ yarn add @rustable/commons
pnpm add @rustable/commons
```

## Collections
## 📚 Collections

### HashMap<K, V>

Expand All @@ -41,9 +40,10 @@ map.insert('key', 1);
const value = map.get('key').unwrapOr(0);

// Entry API for safe insertion
map.entry('key')
.and_modify(v => v + 1)
.or_insert(0);
map
.entry('key')
.and_modify((v) => v + 1)
.or_insert(0);

// Iterate over entries
for (const [k, v] of map) {
Expand Down Expand Up @@ -85,7 +85,7 @@ for (const item of set) {

### Vec\<T>

A growable array implementation similar to Rust's Vec<T>.
A growable array implementation similar to Rust's Vec<T>. Provides efficient array operations with dynamic size management.

```typescript
import { Vec } from '@rustable/commons';
Expand All @@ -100,24 +100,52 @@ vec.push(4);
vec.extend([5, 6, 7]);
const last = vec.pop(); // Some(7)

// Vector operations
vec.insert(1, 8);
vec.remove(0);
vec.clear();

// Access elements
const first = vec.first(); // Option<T>
const item = vec.get(1); // Option<T>
vec.insert(0, 0);
const first = vec.get(0); // Option<T>
const firstRef = vec.getMut(0); // Option<Ptr<T>>

// Advanced operations
vec.splice(1, 2); // Remove elements
vec.drain(0, 2); // Remove and get elements
vec.retain(x => x % 2 === 0); // Keep even numbers

// Iterator methods
vec
.iter()
.map(x => x * 2)
.filter(x => x > 2)
.collect(); // Create new Vec
vec.retain((x) => x > 3); // Keep only elements > 3
vec.dedup(); // Remove consecutive duplicates
vec.sort(); // Sort in ascending order
```

### IdxVec\<T>

An extension of Vec<T> that provides array-like index access. Useful when you need direct index access to elements.

```typescript
import { IdxVec } from '@rustable/commons';

// Create a new indexed vector
const vec = IdxVec.new<number>();
vec.extend([1, 2, 3, 4, 5]);

// Array-like index access
console.log(vec[0]); // 1
vec[1] = 10; // Direct assignment
console.log(vec[1]); // 10

// Still has all Vec<T> operations
vec.push(6);
vec.sort((a, b) => b - a); // Sort in descending order
vec.retain((x) => x % 2 === 0); // Keep only even numbers

// Efficient slicing
const slice = vec.slice(1, 3); // Get elements from index 1 to 3

// Advanced operations
const [left, right] = vec.splitAtUnchecked(2); // Split vector at index
vec.splice(1, 2, [10, 20]); // Replace elements
```

> 💡 Note: Use `Vec` when you need efficient array operations and don't require index access. Use `IdxVec` when you need array-like index access or are working with code that expects array-like behavior.
## Traits

### Clone Trait
Expand Down Expand Up @@ -240,13 +268,13 @@ interface NumberRange extends Iter<number> {}

const range = new NumberRange(1, 5);
const doubledEvenSum = range
.filter(n => n % 2 === 0)
.map(n => n * 2)
.filter((n) => n % 2 === 0)
.map((n) => n * 2)
.sum();

console.log(doubledEvenSum); // 12 (2*2 + 4*2)
```

## License
## 📄 License

MIT © illuxiza
68 changes: 51 additions & 17 deletions packages/enum/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,20 @@

A TypeScript implementation of Rust-style pattern matching, Option, and Result types. This package provides type-safe alternatives to null/undefined and error handling patterns in TypeScript.

## Installation
## ✨ Features

- 🔒 **Type-safe Enums**: Full TypeScript support with proper type inference
- 🎭 **Pattern Matching**: Exhaustive pattern matching with compile-time checks
- 🔄 **Option Type**: Safe handling of optional values without null/undefined
-**Result Type**: Elegant error handling with Ok/Err variants
- 🎯 **Let Pattern**: Type-safe conditional execution with proper inference
- 🔗 **Method Chaining**: Rich set of combinators for value transformation
- 🛡️ **Null Safety**: Complete elimination of null/undefined related bugs
- 🏭 **Factory API**: Easy creation of custom enums with type checking
- 🔄 **Async Support**: First-class support for async operations with Result type
- 📦 **Zero Dependencies**: No external runtime dependencies

## 📦 Installation

```bash
npm install @rustable/enum
Expand All @@ -12,7 +25,7 @@ yarn add @rustable/enum
pnpm add @rustable/enum
```

## Core Components
## 📚 Core Components

### Pattern Matching (`enum.ts`)

Expand Down Expand Up @@ -44,7 +57,6 @@ value.let('Variant1', {
if: (str) => console.log(`Found Variant1: ${str}`),
else: () => console.log('Not Variant1'),
});

```

### Custom Enums (`Enums.create`)
Expand All @@ -61,7 +73,7 @@ const UserState = Enums.create('UserState', {
Suspended: (reason: string) => {},
});

// Or
// Or
const UserState = Enums.create({
LoggedOut: () => {},
LoggedIn: (userId: string, role: string) => {},
Expand All @@ -79,6 +91,11 @@ state2.match({
Suspended: (reason) => console.log(`Account suspended: ${reason}`),
LoggedOut: () => console.log('Please log in'),
});
// or
state2.match({
LoggedIn: (userId, role) => console.log(`User ${userId} is ${role}`),
_: () => console.log('Not logged in'),
});

// Conditional execution with let pattern matching
state2.letLoggedIn({
Expand Down Expand Up @@ -150,26 +167,43 @@ Represents either success (Ok) or failure (Err). A type-safe way to handle opera
```typescript
import { Result } from '@rustable/enum';

// Basic usage
function validateAge(age: number): Result<number, Error> {
return age >= 0 && age <= 120 ? Result.Ok(age) : Result.Err(new Error('Invalid age'));
}

const result = validateAge(25)
.map((age) => age + 1) // Transform if Ok
.unwrapOr(0); // Default if Err
```

## Key Features
// Async operation handling
const asyncResult = await Result.fromAsync<string, Error>(
fetch('https://api.example.com/data').then((res) => res.text()),
);

- **Type Safety**: Full TypeScript support with proper type inference and constructor type parameters
- **Pattern Matching**: Rust-style exhaustive pattern matching with compile-time checks
- **Let Pattern**: Type-safe conditional execution with proper type inference
- **Option Type**: Safe handling of optional values
- **Result Type**: Elegant error handling
- **Method Chaining**: Rich set of combinators for value transformation
- **Null Safety**: Eliminates null/undefined related bugs
if (asyncResult.isOk()) {
console.log('Got data:', asyncResult.unwrap());
} else {
console.error('Failed:', asyncResult.unwrapErr().message);
}

// Function error wrapping
const parseJSON = Result.fromFn<any, Error, [string]>(JSON.parse);

// Success case
const parseResult = parseJSON('{"key": "value"}');
if (parseResult.isOk()) {
console.log('Parsed:', parseResult.unwrap());
}

// Error case
const errorResult = parseJSON('invalid json');
if (errorResult.isErr()) {
console.error('Parse failed:', errorResult.unwrapErr().message);
}
```

## Usage Examples
## 📖 Usage

### Pattern Matching

Expand Down Expand Up @@ -220,21 +254,21 @@ result.match({
result.mapErr((err) => new Error(`Wrapped: ${err.message}`)).unwrapOr(0);
```

## Best Practices
## 📝 Best Practices

1. Use `Option` instead of null/undefined for optional values
2. Use `Result` for operations that may fail
3. Leverage pattern matching for exhaustive case handling
4. Chain methods to transform values safely
5. Always handle both success and failure cases explicitly

## Notes
## 📝 Notes

- All types are immutable and side-effect free
- Pattern matching is exhaustive by default
- Methods follow Rust's naming conventions
- Full TypeScript type inference support

## License
## 📄 License

MIT © illuxiza
Loading

0 comments on commit bcb9b29

Please sign in to comment.