0

Trying to simply insert some element at specific index using insertAt util function from fp-ts but insertAt returns Option<T[]> | NonEmptyArray which returns object like

const x = insertAt(1, 100)([0, 10]) => { _tag: "someTag", value: [0, 100, 10] }

and I can't just print x.value because Option or NonEmptyArray type have no 'value' key. How can I get access to the whole array to for example render it in a view? How can I iterate through them? fp-ts documentation gives me absolutely 0 knowledge about how it works.

elzoy
  • 5,237
  • 11
  • 40
  • 65
  • FP-TS makes you to be explicit about the fact that an insert operations on arrays may fail by wrapping the result in a value of type `Option`. Getting the value, which maybe is there, out of the wrapper is the intuitive next step. Don't. Leave it inside and apply it with functor or combine it with applicative/monad. –  Nov 24 '22 at 10:07

1 Answers1

0

It's not easy to get started with fp-ts and the answer doesn't mean to deeply explain it, but in short: you need a way to get the value from that option, if there's any.

Here's an example with a brief explanation:

import { insertAt } from 'fp-ts/lib/Array';
import { pipe } from 'fp-ts/lib/function';
import { option as O } from 'fp-ts';

const x = pipe( // 1
  [0, 10],
  insertAt(1, 100),
  O.getOrElse(() => []) // 2
);
  1. I used pipe to transform the initial value and apply all the needed functions.
    You could also use flow, which returns a function instead and you must pass your array as an argument.
    const x = flow(
      insertAt(1, 100),
      O.getOrElse(() => [])
    )([0, 10]);
    
  2. Here you can see an example on how to retrieve the value. Since the value in option can be "none" or "some", you need a way to get a fallback value.
    An example for the "none" case:
    const x = pipe(
      [0, 10],
      insertAt(4, 100), // NOTE: cannot insert at index 4 since the array has 2 items
      O.getOrElse(() => [1000])
    );
    // x === [1000]
    
Giovanni Londero
  • 1,309
  • 1
  • 10
  • 20