oldbros / shiftjs

MIT License
22 stars 4 forks source link

lens #6

Open URVL opened 1 year ago

URVL commented 1 year ago

Availability of lenses in the library? If so, which contract is philosophically preferred?

const profile = {
  name: "John Doe",
  age: 12, 
  about: {
    interests: [
      {title: "JavaScript", priority_force: 10},
      //...
    ]
    //...
  }
}

// array notation
const getProfileInterests = lens(['about', 'interests']) // [...]
// string notation 
const getProfileInterests = lens('about.interests') // [...]
// object dot notaion 
const getProfileInterests = lens((data) => data.about.interests) // [...]

// another variant?

const profileInterests = getProfileInterests(profile)
// If the value is not found, what do we return? undefined or something else?
georgolden commented 1 year ago

@URVL the idea of the lens is to provide getter and setter functions as arguments, not the path to reading data

// Getter and setter must be specified as arguments
const getProfileInterests = (data) => data.about.interests;
const setProfileInterests = (value, data) => ({ ...data, about: { ...data.about, interests: value } });
const profileInterestsLens = lens(getProfileInterests, setProfileInterests);

// Usage for example to extract a value using lens from any given object
const profile = {
  name: 'John Doe',
  age: 12,
  about: {
    interests: [
      { title: 'JavaScript', 'priority_force': 10 },
      //...
    ],
    //...
  },
};

const profileInterests = view(profileInterestsLens, profile);
// Output -> [ { title: 'JavaScript', priority_force: 10 } ]
const newProfile = set(profileInterestsLens, null, profile);
// Output -> { name: 'John Doe', age: 12, about: { interests: null } }

In other words - lens is a functional replacement for OOP getters and setters.

Differences:

What you are suggesting here is not particularly a lens - it just a way to create a getter for nested objects

URVL commented 1 year ago

whether it is possible to apply partially: lens -? view -? set -?

georgolden commented 1 year ago

everything is curriable and compsoable

georgolden commented 1 year ago

@URVL are you planning to implement lens and functions to operate with it?