- Mar 2023
-
z-pattern-matching.github.io z-pattern-matching.github.io
-
- Matches by Object property ```js const { matches } = require('z')
const person = { name: 'Maria' } matches(person)( (x = { name: 'John' }) => console.log('John you are not welcome!'), (x) => console.log(
Hey ${x.name}, you are welcome!
) )- Matches by type or instances
js const { matches } = require('z')const result = matches(1)( (x = 2) => 'number 2 is the best!!!', (x = Number) =>
number ${x} is not that good
, (x = Date) => 'blaa.. dates are awful!' )console.log(result) // output: number 1 is not that good
- Matches Array content
js const { matches } = require('z')matches([1, 2, 3, 4, 5])( (a, b, c, tail) => 'a = 1, b = 2, c = 3, tail = [4, 5]'<br /> )
matches([1, 2])( (a, tail) => 'a = 1, tail = [2]'<br /> )
matches([1])( (a, b, tail) => 'Will not match here', (a = 2, tail = []) => 'Will not match here', (a = 1, tail) => 'Will match here, tail = []' ) ```
- Powerful recursive code which will remove sequential repeated items from Array ```js const { matches } = require('z')
const compress = (numbers) => { return matches(numbers)( (x, y, xs) => x === y ? compress([x].concat(xs)) : [x].concat(compress([y].concat(xs))), (x, xs) => x // stopping condition ) }
compress([1, 1, 2, 3, 4, 4, 4]) //output: [1, 2, 3, 4] ```
Tags
Annotators
URL
-