Extcy Operations
In this chapter, we will learn how to use operations such as pattern matching
, cond
, pipe
'ing and more.
Pattern Matching
const person1 = {
name: "Alice",
age: 30,
address: {
city: "San Francisco",
state: "California",
},
};
const pattern1 = {
name: "Alice",
age: (age: number) => age >= 30,
address: { state: "California" },
};
console.log(match(person1, pattern1)); // true
The match operator is not only used to match against simple values, but it is also useful for destructuring more complex data types.
When
const result = when(
11,
[(n) => n === 0, () => "zero"],
[(n) => n % 2 === 0, () => "even"],
[(n) => n % 2 !== 0, () => "odd"]
);
console.log(result); // odd
Cond
const result = cond<number>(3,
{ predicate: (value) => value === 1, result: 'one' },
{ predicate: (value) => value === 2, result: 'two' },
{ predicate: (value) => value === 3, result: 'three' },
{ predicate: (value) => value === 4, result: 'four' },
{ predicate: (value) => value === 5, result: 'five' },
);
console.log(result); // => "three"
Pipe
// functions for numbers
const addOne = (n: number) => n + 1;
const double = (n: number) => n * 2;
const square = (n: number) => n * n;
// functions for strings
const concatenate = (s: string) => s + ' World';
const toUpperCase = (s: string) => s.toUpperCase();
// functions for arrays
const reverseArray = (arr: unknown[]) => [...arr].reverse();
const sortArray = (arr: unknown[]) => [...arr].sort();
// numbers
const result1 = pipe<number>(addOne, double, square)(3);
console.log(result1); // => 64
// strings
const result2 = pipe<string>(concatenate, toUpperCase)('Hello');
console.log(result2); // => "HELLO WORLD"
// arrays
const result3 = pipe<unknown[]>(reverseArray, sortArray)([4, 6, 5, 2]);
console.log(result3); // => "[2, 4, 5, 6]"
Sigil
const capitalizedWords = sigil(/([A-Z]\w+)/g, "hello world this is a test");
const numbers = sigil(/\d+/g, "I have 3 apples and 5 oranges.");
console.log(capitalizedWords); // ["Hello", "World", "This", "Is", "A", "Test"]
console.log(numbers); // ["3", "5"]
🥳 Awesome! Remember that these are just really simple examples. If you want to see more examples, feel free to check out example
folder.