Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
monocle-ts
Advanced tools
monocle-ts is a library for functional programming in TypeScript that provides tools for working with immutable data structures. It offers optics such as lenses, prisms, and traversals to facilitate the manipulation and querying of deeply nested data in a type-safe manner.
Lens
Lenses are used to focus on a specific part of a data structure. In this example, a lens is created to focus on the 'city' property within the 'address' object of a 'person'. The lens is then used to update the city to 'Los Angeles'.
const { Lens } = require('monocle-ts');
const person = { name: 'John', address: { city: 'New York' } };
const addressLens = Lens.fromPath(['address', 'city']);
const newPerson = addressLens.set('Los Angeles')(person);
console.log(newPerson); // { name: 'John', address: { city: 'Los Angeles' } }
Prism
Prisms are used to focus on a part of a data structure that may or may not be present. In this example, a prism is created to focus on the 'Some' case of an option type. The prism is then used to extract the value if it exists.
const { Prism } = require('monocle-ts');
const some = (value) => ({ _tag: 'Some', value });
const none = { _tag: 'None' };
const optionPrism = Prism.fromPredicate((s) => s._tag === 'Some');
const result = optionPrism.getOption(some(42));
console.log(result); // { _tag: 'Some', value: 42 }
Traversal
Traversals are used to focus on multiple parts of a data structure. In this example, a traversal is created to focus on each element of an array. The traversal is then used to double each number in the array.
const { fromTraversable, array } = require('monocle-ts');
const numbers = [1, 2, 3, 4];
const traversal = fromTraversable(array)();
const newNumbers = traversal.modify((n) => n * 2)(numbers);
console.log(newNumbers); // [2, 4, 6, 8]
Ramda is a practical functional library for JavaScript developers. It provides a wide range of functions for working with immutable data, including lenses and traversals. Compared to monocle-ts, Ramda is more general-purpose and less focused on TypeScript's type safety.
Immutable.js provides persistent immutable data structures for JavaScript. It offers a different approach to immutability by providing its own data structures rather than focusing on optics like monocle-ts. Immutable.js is more about providing efficient immutable collections.
fp-ts is a library for functional programming in TypeScript. It provides a wide range of functional programming tools, including optics similar to those in monocle-ts. fp-ts is more comprehensive and includes many other functional programming utilities beyond optics.
A (partial) porting of scala monocle library to TypeScript
(Adapted from monocle site)
Modifying immutable nested object in JavaScript is verbose which makes code difficult to understand and reason about.
Let's have a look at some examples:
interface Street { num: number, name: string }
interface Address { city: string, street: Street }
interface Company { name: string, address: Address }
interface Employee { name: string, company: Company }
Let’s say we have an employee and we need to upper case the first character of his company street name. Here is how we could write it in vanilla JavaScript
const employee: Employee = {
name: "john",
company: {
name: "awesome inc",
address: {
city: "london",
street: {
num: 23,
name: "high street"
}
}
}
}
function capitalize(s: string): string {
return s.substring(0, 1).toUpperCase() + s.substring(1)
}
const employee2 = {
...employee,
company: {
...employee.company,
address: {
...employee.company.address,
street: {
...employee.company.address.street,
name: capitalize(employee.company.address.street.name)
}
}
}
}
As we can see copy is not convenient to update nested objects because we need to repeat ourselves. Let's see what could we do with monocle-ts
import { Lens, Optional } from 'monocle-ts'
const company = Lens.fromProp<Employee, 'company'>('company')
const address = Lens.fromProp<Company, 'address'>('address')
const street = Lens.fromProp<Address, 'street'>('street')
const name = Lens.fromProp<Street, 'name'>('name')
company.compose(address).compose(street).compose(name)
compose
takes two Lenses
, one from A
to B
and another one from B
to C
and creates a third Lens
from A
to C
.
Therefore, after composing company
, address
, street
and name
, we obtain a Lens
from Employee
to string
(the street name).
Now we can use this Lens
issued from the composition to modify the street name using the function capitalize
company
.compose(address)
.compose(street)
.compose(name)
.modify(capitalize, employee)
Here modify
lift a function string => string
to a function Employee => Employee
. It works but it would be clearer if we could zoom
into the first character of a string
with a Lens
. However, we cannot write such a Lens
because Lenses
require the field they are directed
at to be mandatory. In our case the first character of a string
is optional as a string
can be empty. So we need another abstraction that
would be a sort of partial Lens, in monocle-ts
it is called an Optional
.
import { some, none } from 'fp-ts/lib/Option'
const firstLetter = new Optional<string, string>(
s => s.length > 0 ? some(s[0]) : none,
(a, s) => a + s.substring(1)
)
company
.compose(address)
.compose(street)
.compose(name)
.asOptional()
.compose(firstLetter)
.modify(s => s.toUpperCase(), employee)
Similarly to compose
for lenses, compose
for optionals takes two Optionals
, one from A
to B
and another from B
to C
and creates a third Optional
from A
to C
.
All Lenses
can be seen as Optionals
where the optional element to zoom into is always present, hence composing an Optional
and a Lens
always produces an Optional
.
0.1.0
Initial release
FAQs
A porting of scala monocle library to TypeScript
The npm package monocle-ts receives a total of 326,140 weekly downloads. As such, monocle-ts popularity was classified as popular.
We found that monocle-ts demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.