Skip to Content
Mastering JavaScript Functional Programming - Second Edition
book

Mastering JavaScript Functional Programming - Second Edition

by Federico Kereki
January 2020
Intermediate to advanced
470 pages
11h 13m
English
Packt Publishing
Content preview from Mastering JavaScript Functional Programming - Second Edition

Implementing prisms

How do we implement prisms? We will take our cue from our lenses implementation and make a few changes. When getting an attribute, we must check whether the object we are processing is not null or undefined and whether the attribute we want is in the object. We can make do by making small changes to our original getField() function:

const getFieldP = curry((attr, obj) =>  obj && attr in obj ? obj[attr] : undefined);

Here, we're checking for the existence of the object and the attribute: if everything's fine, we return obj[attr]; otherwise, we return undefined otherwise. The changes for setField() are very similar:

const setFieldP = curry((attr, value, obj) =>  obj && attr in obj ? { ...obj, [attr]: value } : { ...obj }
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Functional Programming

Mastering JavaScript Functional Programming

Federico Kereki

Publisher Resources

ISBN: 9781839213069Supplemental Content