Skip to content

key lens with a default value #49

@hanazuki

Description

@hanazuki

🚀 Feature request

Current Behavior

This may be just a newbie question as I'm not familiar with fp-ts or effect-ts library, or the notion of Optics in general...

I want to read and write a property in a nested object that may not exist, as illustrated in the following snippet.

// We have a set of counters. Each counter is assigned a string key.
type Counters = { [key: string]: { counter: number } }

// At the beginning, we only have the 'foo' counter in the set.
const c: Counters = { foo: { counter: 1 } }

// This is what I want.
export const keyWithDefault = <S extends object, Key extends keyof S & (string | symbol)>(key: Key, fallback: () => S[Key]): Optic.Lens<S, S[Key]> =>
  Optic.lens(
    (s) => Object.prototype.hasOwnProperty.call(s, key) ? s[key] : fallback(),
    (b) => (s) => ({ ...s, [key]: b }),
  )


// This lens focuses on the 'bar' counter, whether it exists or not.
const _bar = Optic.id<Counters>().compose(keyWithDefault('bar', () => ({ counter: 0 }))).at('counter')
 
// Because 'bar' doesn't exist, the fallback value is used when accessed.
console.log(Optic.get(_bar)(c))  // => 0
console.log(Optic.replace(_bar)(3)(c))  // => { foo: { counter: 1 }, bar: { counter: 3 } }
console.log(Optic.modify(_bar)(n => n + 5)(c))  // => { foo: { counter: 1 }, bar: { counter: 5 } }

Desired Behavior

Can this be achieved by composing the existing optics in the library, instead of implementing keyWithDefault by myself?

Suggested Solution

Add an overload of the key function that takes a fallback value and returns a lens.

Who does this impact? Who is this for?

I suppose using an Object as a dictionary/map is idiomatic in TypeScript/JavaScript and this is useful in many situations.

Describe alternatives you've considered

The proposed function can be easily implemented on the user side as shown in the code snippet. (edited the code; Actually, I happened to know this might not be as easy to implement properly as I think...)

Additional context

Your environment

Software Version(s)
@fp-ts/optic 0.10.0
TypeScript 5.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions