In functional programming, the Lenses pattern offers a solution for handling data manipulation in an immutable way. A Lens essentially serves as a first-class reference to a subpart of some data type. Despite its regular use in languages with built-in support for lenses (e.g. Haskell), a JavaScript developer can still incorporate the lens pattern via libraries or custom implementations.
This blog post will explore the lenses pattern and demonstrate how you can implement it in JavaScript to work with deeply nested paths.
What is a Lens?
A Lens is a functional pattern used to manage immutable data operations. They let us “zoom in”, or focus, on a particular part of a data structure (like an object or an array). Every lens consists of two functions: a getter and a setter.
Getter Function: Retrieves a sub-part of the data.
Setter Function: Updates a sub-part of the data in an immutable way.
An important feature of lenses is that they compose, meaning lenses focusing on nested data can be effectively chained to manipulate a required piece of data.
Implementing Lenses in JavaScript
Even though JavaScript doesn’t provide built-in support for lenses, we can create a custom lens function to achieve similar functionality. A basic lens function involves creating a getter and setter to retrieve and update the data respectively.
Let’s start simple and create a lens that is not dynamic, meaning it works with a single predetermined path:
function lens(getter, setter) { return { get: getter, set: setter }; }
But the real power of lenses comes when we make them handle deeply nested paths. To achieve that, we make our lens function accept a path (an array of keys), and modify our getter and setter to navigate the object using this path:
function lens(path) { return { get: (object) => path.reduce((obj, key) => obj && obj[key], object), set: (value, object) => { const setObjectAtKeyPath = (obj, path, value) => { if (path.length === 1) { return { ...obj, [path[0]]: value }; } const key = path[0]; return { ...obj, [key]: setObjectAtKeyPath(obj[key] || {}, path.slice(1), value) }; }; return setObjectAtKeyPath(object, path, value); }, }; }
To use this lens, we create a path array indicating the sequence of keys to the desired property, and pass this path to the lens function. The returned lens object provides get and set methods for reading and updating the property:
const person = { name: "John Doe", address: { street: "123 Main St", city: "Any town", country: "USA" }, };
// Create a lens for the address.street path: const streetLens = lens(["address", "street"]);
// Get street using the lens: console.log(streetLens.get(person)); // Outputs: 123 Main St
// Set street using the lens, resulting in a new (immutable) object: const newPerson = streetLens.set("456 Broadway St", person); console.log(newPerson); // Outputs the new person object with the updated street
Conclusion
The lenses pattern rewards developers with the ability to maintain immutability while easily accessing and updating deeply nested data structures. The effectiveness and elegance of lenses are in their composability and the simplicity of resulting code. While JavaScript does not support lenses natively, we’ve seen how to produce a lens like behaviour using array methods and recursion. However, for simplification, this custom implementation does not handle edge cases that established libraries do. Thus, for production-level code, consider using libraries such as Ramda or partial.lenses that offer more comprehensive lens functionalities.
Link to my original article:
https://dev.to/ashutosh_mathur/understanding-and-implementing-the-lenses-pattern-in-javascript-333a
#Javascript #functional-architecture-pattern #frontend #ramda
141 Comments
Your article helped me a lot, is there any more related content? Thanks!
Thank you ever so for you article.Really looking forward to read more. Want more.
Thanks , I’ve recently been searching for information about this topic for ages and yours is the greatest I’ve discovered till now. But, what about the conclusion? Are you sure about the source?
lasix india I JOURNAL everything I eat and keep track of my calories
Really a lot of very good data.graphic organizers for writing essays write my essay professional personal statement writing services
Your people are more likely to respond to offers made via mobile messages. The old standbys have to be fed, but they won’t fuel a growth rebound. However it’s not actually free – you shell outside in decreased security.
Hi there, just became alert to your blog through Google, and found that it’s really informative.I’m going to watch out for brussels. I’ll appreciate if you continue this in future.Lots of people will be benefited from your writing.Cheers!
My brother recommended I might like this blog. He was totally right.This post actually made my day. You cann’t believesimply how much time I had spent for this info! Thanks!
It’s really a nice and useful piece of information. I am glad that you simply shared this useful info with us. Please stay us up to date like this. Thank you for sharing.
Thank you, I’ve just been looking for information about this subject for a long time and yours is the best I’ve discovered till now.But, what about the bottom line? Are you positive aboutthe supply?
I really like and appreciate your blog article.Much thanks again. Much obliged.
Fantastic blog article. Fantastic.
Very neat blog article.Really thank you! Really Cool.
Very neat article. Want more.
Hey, thanks for the blog post.Thanks Again. Keep writing.
Thanks again for the article post. Much obliged.
modalert online provigil side effects Loading…
Thanks-a-mundo for the blog.Really looking forward to read more. Want more.
I appreciate you sharing this post.Thanks Again. Really Cool.
Thanks again for the blog article.Really looking forward to read more. Cool.
Remarkable issues here. I am very happy to look your post.Thank you so much and I am having a look ahead to touch you.Will you please drop me a mail?
Thanks for any other wonderful article. The place else could anybody get that kind of information in such a perfect manner of writing? I have a presentation subsequent week, and I’m at the look for such info.
A round of applause for your blog article.Much thanks again. Want more.
Highly descriptive blog, I loved that bit. Will there bea part 2?
Really appreciate you sharing this article post.Much thanks again. Really Great.
Appreciate you sharing, great article.Really thank you! Fantastic.
I really like what you guys are usually up too. This type of clever workand reporting! Keep up the terrific works guys I’ve included you guys to our blogroll.
Have you got any ? coumadin bracelet “The weather has continued to present problems for the pitch and the first consideration of both the HKFA and Manchester United has to be the safety of the players in such conditions.”
sito meraviglioso sarà tenerli a preferiti saluti
Great info and straight to the point. I am not sure if this is truly the best place to ask but do you people have any thoughts on where to employ some professional writers? Thank you 🙂
Greetings! Very useful advice within this post! It is the little changes which will make the greatest changes. Thanks a lot for sharing!
top farmacia online: Farma Prodotti – Farmacia online miglior prezzo
Farmacia online piГ№ conveniente
kamagra pills: male erectile pills over the counter ed medication
Appreciate you sharing, great blog post.Really thank you! Cool.
http://farmaprodotti.com/# farmacia online piГ№ conveniente
farmacia online
comprare farmaci online all’estero: Brufen senza ricetta – farmacie online autorizzate elenco
top farmacia online https://farmaprodotti.com/# Farmacia online miglior prezzo
farmaci senza ricetta elenco
taya777 taya777 app Players enjoy both fun and excitement in casinos.
The casino atmosphere is thrilling and energetic. http://phtaya.tech/# The poker community is very active here.
Los jugadores deben jugar con responsabilidad.: jugabet – jugabet casino
https://phmacao.life/# Live music events often accompany gaming nights.
Gambling regulations are strictly enforced in casinos.
taya777 app taya777.icu The ambiance is designed to excite players.
Los casinos organizan noches de trivia divertidas.: jugabet chile – jugabet
http://taya777.icu/# Gambling can be a social activity here.
Casinos offer delicious dining options on-site.
Visitors come from around the world to play. https://taya365.art/# The Philippines has a vibrant nightlife scene.
The casino experience is memorable and unique.: taya365 – taya365 login
http://taya365.art/# The casino industry supports local economies significantly.
Gambling regulations are strictly enforced in casinos.
Players enjoy both fun and excitement in casinos. https://winchile.pro/# La pasiГіn por el juego une a personas.
Casinos often host special holiday promotions.: taya365 com login – taya365 login
https://phtaya.tech/# A variety of gaming options cater to everyone.
Visitors come from around the world to play.
http://winchile.pro/# Los juegos de mesa son clГЎsicos eternos.
Casino visits are a popular tourist attraction.
Many casinos offer luxurious amenities and services. https://phtaya.tech/# Slot machines attract players with big jackpots.
The Philippines has several world-class integrated resorts.: taya777 register login – taya777 register login
win chile winchile Los casinos celebran festivales de juego anualmente.
http://taya365.art/# п»їCasinos in the Philippines are highly popular.
Many casinos host charity events and fundraisers.
Players can enjoy high-stakes betting options.: taya777.icu – taya777 login
Some casinos have luxurious spa facilities. https://taya777.icu/# Casino promotions draw in new players frequently.
http://taya777.icu/# Most casinos offer convenient transportation options.
Online gaming is also growing in popularity.
Many casinos have beautiful ocean views.: taya365.art – taya365.art
Resorts provide both gaming and relaxation options. https://phtaya.tech/# Security measures ensure a safe environment.
http://phmacao.life/# п»їCasinos in the Philippines are highly popular.
Slot tournaments create friendly competitions among players.
Las promociones atraen nuevos jugadores diariamente.: winchile.pro – winchile casino
The casino atmosphere is thrilling and energetic. https://phmacao.life/# Casino visits are a popular tourist attraction.
https://phtaya.tech/# Casinos often host special holiday promotions.
The Philippines offers a rich gaming culture.
winchile casino winchile casino Los jugadores deben jugar con responsabilidad.
Cashless gaming options are becoming popular.: taya777 app – taya777
Live dealer games enhance the casino experience. http://phtaya.tech/# Some casinos have luxurious spa facilities.
https://taya777.icu/# Entertainment shows are common in casinos.
Many casinos have beautiful ocean views.
jugabet chile jugabet chile La historia del juego en Chile es rica.
https://phtaya.tech/# Casino promotions draw in new players frequently.
Most casinos offer convenient transportation options.
http://taya365.art/# Live dealer games enhance the casino experience.
Loyalty programs reward regular customers generously.
https://phtaya.tech/# Gambling regulations are strictly enforced in casinos.
The thrill of winning keeps players engaged.
http://taya777.icu/# Entertainment shows are common in casinos.
Gaming regulations are overseen by PAGCOR.
Casino promotions draw in new players frequently.: taya365 login – taya365 com login
jugabet chile jugabet.xyz Los jugadores deben conocer las reglas.
Los casinos reciben turistas de todo el mundo.: jugabet casino – jugabet
https://winchile.pro/# Las apuestas mГnimas son accesibles para todos.
Gambling regulations are strictly enforced in casinos.
Many casinos have beautiful ocean views.: taya365 com login – taya365 com login
http://winchile.pro/# La competencia entre casinos beneficia a los jugadores.
Slot machines feature various exciting themes.
phtaya casino [url=http://phtaya.tech/#]phtaya.tech[/url] The Philippines has a vibrant nightlife scene.
Los jugadores deben conocer las reglas.: winchile casino – winchile
What’s up, yes this article is truly fastidious and Ihave learned lot of things from it on the topic of blogging.thanks.
I loved your blog.Much thanks again. Much obliged.
Manila is home to many large casinos.: taya777 login – taya777.icu
The poker community is very active here. http://phtaya.tech/# Slot machines attract players with big jackpots.
https://phtaya.tech/# Live dealer games enhance the casino experience.
Many casinos have beautiful ocean views.
Players often share tips and strategies.: taya777 login – taya777 register login
https://taya365.art/# Visitors come from around the world to play.
Responsible gaming initiatives are promoted actively.
The casino experience is memorable and unique.: phtaya – phtaya casino
Loyalty programs reward regular customers generously.: phmacao club – phmacao club
winchile casino winchile La Г©tica del juego es esencial.
xxl mexican pharm best online pharmacies in mexico xxl mexican pharm
canadian pharmacy coupon code https://xxlmexicanpharm.com/# xxl mexican pharm
MegaIndiaPharm: pharmacy website india – cheapest online pharmacy india
canadian pharmacy world coupon code http://discountdrugmart.pro/# drugmart
mexico drug stores pharmacies buying prescription drugs in mexico online xxl mexican pharm
Hey! Awesome! thank you for this very good blog post.เว็บพนันบอล ออนไลน์
online canadian pharmacy coupon https://xxlmexicanpharm.com/# xxl mexican pharm
Best online pharmacy: family pharmacy – family pharmacy
rx pharmacy no prescription https://megaindiapharm.com/# world pharmacy india
discount drugs: discount drug mart pharmacy – drug mart
prescription drugs online https://xxlmexicanpharm.com/# pharmacies in mexico that ship to usa
xxl mexican pharm xxl mexican pharm mexican border pharmacies shipping to usa
canadian neighbor pharmacy: easy canadian pharm – reliable canadian online pharmacy
cheapest pharmacy to get prescriptions filled https://familypharmacy.company/# family pharmacy
rx pharmacy no prescription https://megaindiapharm.shop/# reputable indian online pharmacy
easy canadian pharm: northwest canadian pharmacy – precription drugs from canada
discount drug mart: canadian pharmacy no prescription needed – discount drug mart
cheapest pharmacy for prescription drugs https://familypharmacy.company/# family pharmacy
best no prescription pharmacy https://easycanadianpharm.com/# canada pharmacy reviews
easy canadian pharm easy canadian pharm easy canadian pharm
canadian online pharmacy no prescription http://easycanadianpharm.com/# easy canadian pharm
online pharmacy no prescription: Best online pharmacy – uk pharmacy no prescription
cheapest pharmacy for prescription drugs https://familypharmacy.company/# drugstore com online pharmacy prescription drugs
reputable online pharmacy no prescription: Cheapest online pharmacy – canadian pharmacy discount code
online pharmacy no prescription https://familypharmacy.company/# online pharmacy delivery usa
Cheapest online pharmacy: online pharmacy delivery usa – online pharmacy delivery usa
canadian pharmacy without prescription https://familypharmacy.company/# rxpharmacycoupons
MegaIndiaPharm Mega India Pharm reputable indian pharmacies
Mega India Pharm: п»їlegitimate online pharmacies india – MegaIndiaPharm
buying prescription drugs from canada https://familypharmacy.company/# Cheapest online pharmacy
online pharmacy without prescription http://easycanadianpharm.com/# online canadian drugstore
pharmacy coupons http://easycanadianpharm.com/# easy canadian pharm
prescription drugs online https://megaindiapharm.shop/# MegaIndiaPharm
family pharmacy Online pharmacy USA online pharmacy delivery usa
I like what you guys are up too. Such smart work and reporting! 온라인카지노
purple pharmacy mexico price list: xxl mexican pharm – buying prescription drugs in mexico
online pharmacy discount code http://discountdrugmart.pro/# discount drug pharmacy
Cheapest online pharmacy: family pharmacy – Cheapest online pharmacy
online canadian pharmacy coupon https://familypharmacy.company/# Best online pharmacy
mexican online pharmacies prescription drugs xxl mexican pharm buying prescription drugs in mexico online
canadian pharmacy world coupon https://xxlmexicanpharm.shop/# xxl mexican pharm
online pharmacy delivery usa: Online pharmacy USA – canadian online pharmacy no prescription
canadian pharmacy world coupons http://xxlmexicanpharm.com/# medicine in mexico pharmacies
overseas pharmacy no prescription https://xxlmexicanpharm.com/# buying prescription drugs in mexico
online pharmacy non prescription drugs https://megaindiapharm.shop/# MegaIndiaPharm
Mega India Pharm MegaIndiaPharm п»їlegitimate online pharmacies india
canadian pharmacy discount coupon https://discountdrugmart.pro/# discount drug mart pharmacy
canadian pharmacy no prescription http://familypharmacy.company/# Online pharmacy USA
online canadian pharmacy coupon https://xxlmexicanpharm.com/# xxl mexican pharm
Online pharmacy USA online pharmacy delivery usa family pharmacy