Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple example of nice, clean lens composition in ramda using a helper
const nameLens = R.lensProp('name');
const user = {
name: 'Joe',
age: 34,
isLoggedIn: true,
address: {
number: 123,
street: 'best'
}
};
const lensCreator = lens => transform => user => ({
get: () => R.view(lens, user),
set: (newName) => R.set(lens, newName, user),
transform: () => R.over(lens, transform, user)
});
const transformAddress = input => `${input} street`;
const usersName = lensCreator(nameLens)(input => input.toLowerCase());
let currentUsersNameLens = usersName(user);
console.log('1: ' + currentUsersNameLens.get());
currentUsersNameLens = usersName(currentUsersNameLens.set('BoB'));
console.log('2: ' + currentUsersNameLens.get());
currentUsersNameLens = usersName(currentUsersNameLens.transform());
console.log('3: ' + currentUsersNameLens.get());
const addressLens = R.lensProp('address');
const streetLens = R.lensProp('street');
const usersStreetLens = R.compose(addressLens, streetLens);
const usersStreet = lensCreator(usersStreetLens)(transformAddress);
const newUsersStreet = usersStreet(user).transform();
console.log('addr: ', usersStreet(user).get());
console.log('new addr: ', usersStreet(newUsersStreet).get());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.