Katxupa
  • 👋Welcome to Katxupa Extension Library
  • Why Katxupa?
    • 🍻What makes Katxupa special?
    • ✨Key Features
  • Get a taste of Katxupa
    • 🍲Installation
    • 🍜Usage
      • 🍻Scope Functions
        • Function Selection
        • Distinctions
        • Functions
          • letIt
          • withIt
          • runIt
          • applyIt
          • alsoIt
          • takeIf and takeUnless
      • 😎Null Safety
        • TypeScript Null-Safety
        • Optional Chaining for JavaScript
      • ⏰Duration
      • ➖Reducer
      • 📏Range
      • 🏃‍♂️Result
      • 🤼Either
      • 🟰Compare
      • ⚔️Global Utility Functions
    • 🤌Dip Dive
      • Optional
      • Range
      • Duration
      • Reducer
      • Collections
        • Array
        • Set
  • 🙏Support
    • Source Code
    • ESLint Config
    • TypeScript Docs
    • Manuel Santos Linkedin
Powered by GitBook
On this page
  1. Why Katxupa?

What makes Katxupa special?

  • Functional Delight: Katxupa introduces functional programming concepts to enhance your code's expressiveness and clarity.

  • Kotlin-Inspired Goodness: Leveraging lessons learned from Kotlin, Katxupa provides utilities and extensions that streamline your workflow.

  • Boosted Productivity: Enjoy a more productive development experience with Katxupa's utility classes, sequences, durations, and more.

  • Developer Happiness: Inspired by the joy of coding in Kotlin, Katxupa seeks to bring happiness to your TypeScript and JavaScript projects.

function main() {

    ({name: "Manuel Santos", email: "ney.br.santos@gmail.com", age: 35})
        .letIt(it => {
            console.log(`${it.name},`);
            it.age < 30 ? console.log("A Young Man") : console.log("An Old Man");
            return it.age;
        }).alsoIt(it => {
            console.log(`Actual Age is ${it}`);
        })
        .years()
        .runIt((days, hours, minutes, seconds, nanoseconds) => {
            return `Current Age: ${days}d ${hours}h ${minutes}m ${seconds}s ${nanoseconds}ns`;
        })
        .runIt(function() {
            console.log(this);
        });

    // Output:
    //      Manuel Santos,
    //      An Old Man
    //      Actual Age is 35
    //      Current Age: 12783d 18h 0m 0s 0ns
}
  public async updateUser(userId: number, userData: UpdateUserDto): Promise<User> {
    const user = await this.userRepository.findOneBy({
        id: userId,
    });

    return optionalOf(user)
        .orElseThrow(() => new HttpError(409, "User doesn't exist"))
        .map(user => {
            return {
                ...user,
                userData,
            };
        })
        .runAsync(user => this.userRepository.save(user));
}
test('duration', () => {
    const duration = (1).years().add((6).months()).toString();
    expect(duration).toBe("547d 21h 0m 0s 0ns");
});

test('optional', () => {
    const value = 42;
    const optional = Optional.of(value);
    const result = optional.filter((x) => x === 42);
    expect(result.isPresent()).toBe(true);
    expect(result.get()).toBe(value);
});


test('reducer', () => {
    const people = [
      { name: 'Alice', age: 30 },
      { name: 'Bob', age: 25 },
      { name: 'Charlie', age: 35 }
    ];
    const minOfAge = reducerOf(people)
        .minOfWith((person) => person.age, (a, b) => a - b);    
    expect(minOfAge).toEqual({ name: 'Bob', age: 25 });
});

test('range', () => {
    const result = rangeTo(1, 5);
    expect(result).toEqual([1, 2, 3, 4, 5]);
});

test('result', () => {
    const okInstance = Ok.ok(5);
    const mappedResult = okInstance.flatMap(value => Ok.ok(value * 2));
    expect(mappedResult instanceof Ok).toBe(true);
    expect(mappedResult.get()).toBe(10);
});

test('collection', () => {
    type User = { name:string; age:number; }
    
    const sortedUsers = mutableListOf<User>([
        { name: 'John', age: 30 },
        { name: 'Alice', age: 25 },
        { name: 'Bob', age: 35 },
    ]).sortBy((a, b) => a.age - b.age);
    
    expect(sortedUsers)
    .toEqual([
        { name: 'Alice', age: 25 },
        { name: 'John', age: 30 },
        { name: 'Bob', age: 35 },
    ]);
});
test('set extensions', () => {
    const squaredSet = mutableSetOf<number>(1, 2, 3)
        .map((num) => num * num)
        .filter((num) => num % 2 !== 0);
    expect(squaredSet).toEqual(setOf(1, 9));
});

test('array extensions', () => {
    const otherArray = [6, 7, 8];
    let resultArray = [1, 2, 3, 4, 5].plus(otherArray);
    expect(resultArray).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
    
    resultArray = resultArray.removeAll([3, 5])
    expect(resultArray).toEqual([1, 2, 4, 6, 7, 8]);
    
    const element2 = array.getOrElse(9, () => 10);
    expect(element2).toBe(10);
});

test('object extensions', () => {
    const result = "Hello".letIt(value => {
        console.log(value.toUpperCase());
        return value.length;
    });
    expect(result).toBe(5);

    const compResult = "Hello".compareTo("World");
    expect(compResult).toBe(-1);
});
PreviousWelcome to Katxupa Extension LibraryNextKey Features

Last updated 1 year ago

Katxupa extends primitive types (, , ), , , and in order to bring in useful utilities.

🍻
String
Number
Boolean
Array
Set
Map
Object