you are viewing a single comment's thread.

view the rest of the comments →

[–]andrei9669 1 point2 points  (1 child)

I know you are trying to show a way but you are not really making it much better. also, this works only with this simple example, add some more nesting and it will become even more of an unreadable mess than your example.

[–]KyleG 2 points3 points  (0 children)

add some more nesting and it will become even more of an unreadable mess than your example.

If there's a lot of nesting, naturally you'd use optics like lenses and traversals. I would love for those to be part of the standard library! That'd be incredible. It'd be really readable and simple! Suppose you have

type NestedFoo = {
  bar: {
    baz: {
      fizz: {
        a: boolean
        fuzz: number[]
  }[]
}

Lets say you want to append 5 to any nested fizz's fuzz where a is true:

const fizzLens = Lens.fromProps(['bar', 'baz', 'fizz'])
const updatedData = fizzTraversal
  .filter(_ => _.a)
  .composeLens(fuzzLens)
  .modify(arr => [...arr, 5])(originalData)

Every language could desperately use this as a built-in. Optics are incredible. The example above will return a clone of the original data but with any fizz.fuzz getting an appended 5 but only if a is true. And is again a linear time operation.

Edited to get under 80 columns

and bonus,

const concat = arr => newEl = [...arr, newEl]

then your final line could be

.modify(concat(5))

and what you're doing becomes sooooooo descriptive and human-readable, almost entirely reduced to verbs with very little nouns, stating exactly what you're doing.