Skip to content

Instantly share code, notes, and snippets.

@ernestofreyreg
Created May 10, 2022 15:07
Show Gist options
  • Save ernestofreyreg/43d98d997743da208620c55f3c7e5b52 to your computer and use it in GitHub Desktop.
Save ernestofreyreg/43d98d997743da208620c55f3c7e5b52 to your computer and use it in GitHub Desktop.
// Functional Lenses
//
// A functional lens is an object that contains
// two functions, a getter and a setter.
//
// {
// getter: (obj) => any,
// setter: (obj, value) => obj
// }
//
// A functional lens provides access to a property of an object.
//
// A functional lens can be used with any of the following functions
//
// view(lens, any) -> returns the value at the lens
// set(lens, value, any) -> returns the object with the changed value at the lens
// over(lens, fn, any) -> returns the object with the changed value at the lens from the output of the function.
//
//
// Instructions
// 1. Write the 3 functions: `view`, `set`, `over` and tests for it
// 2. Looking at propLens create a indexLens that provides similar behavior on an array.
const assert = require('assert');
function propLens (prop) {
return {
getter: (obj) => obj[prop],
setter: (obj, value) => ({ ...obj, [prop]: value })
}
}
const nameLens = propLens('name')
const person = { name: 'John', last: 'Doe', age: 33 }
console.log(view(nameLens, person)) // 'John'
console.log(set(nameLens, 'Mary', person)) // { name: 'Mary', last: 'Doe', age: 33 }
console.log(over(nameLens, v => v.toUpperCase(), person)) // { name: 'JOHN', last: 'Doe', age: 33 }
console.log(person) // { name: 'John', last: 'Doe', age: 33 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment