Transform the IO type to an array of Either in functional programming with the fp-ts

Looking for assistance with implementing this in fp-ts. Can someone provide guidance?

const $ = cheerio.load('some text');
const tests = $('table tr').get()
  .map(row => $(row).find('a'))
  .map(link => link.attr('data-test') ? link.attr('data-test') : null)
  .filter(v => v != null);

I've managed to work with TaskEither, but I'm unsure how to incorporate IO or if it's necessary. Any suggestions on this front would be appreciated.

Here is what I have so far:

const selectr = (a: CheerioStatic): CheerioSelector => (s: any, c?: any, r?: any) => a(s, c, r);

const getElementText = (text: string) => {
  return pipe(
    IO.of(cheerio.load),
    IO.ap(IO.of(text)),
    IO.map(selectr),
    IO.map(x => x('table tr')),
    // ?? don't know what to do here
  );
}

Update:

The most challenging part for me is transforming the typings from IO to an array of Either, then filtering out or ignoring the lefts and proceeding with Task or TaskEither.

The TypeScript error I encounter is

Type 'Either<Error, string[]>' is not assignable to type 'IO<unknown>'

const getAttr = (attrName: string) => (el: Cheerio): Either<Error, string> => {
  const value = el.attr(attrName);
  return value ? Either.right(value) : Either.left(new Error('Empty attribute!'));
}

const getTests = (text: string) => {
  const $ = cheerio.load(text);
  return pipe(
    $('table tbody'),
    getIO,
    // How to go from IO<string> to IOEither<unknown, string[]> or something similar?
    // What happens to the array of errors do we keep them or we just change the typings?
    IO.chain(rows => A.array.traverse(E.either)(rows, flow($, attrIO('data-test)))),
  );

Answer №1

If you aim to follow best practices, it is essential to encapsulate all non-deterministic (non-pure) function calls within IO or IOEither (depending on their potential failure).

To distinguish between "pure" and non-pure functions, consider this simple rule - if a function consistently produces the same output for the same input without causing any observable side effects, it is deemed pure.

The definition of "same output" does not imply referential equality but rather structural/behavioral equivalence. Therefore, even if a function returns another function that may not be the exact object, it should exhibit identical behavior for the original function to maintain purity.

Based on these criteria, the following classification holds true:

  • cherio.load is a pure function
  • $ is a pure function
  • .get is not pure
  • .find is not pure
  • .attr is not pure
  • .map is pure
  • .filter is pure

To address non-pure function calls, let's create wrappers as follows:

const getIO = selection => IO.of(selection.get())
const findIO = (...args) => selection => IO.of(selection.find(...args))
const attrIO = (...args) => element => IO.of(element.attr(...args))

It's important to note that when applying a non-pure function like .attr or attrIO to an array of elements, mapping attrIO directly would yield Array<IO<result>>, which can be enhanced by using traverse instead of map.

In the case where you want to apply attrIO to an array named

rows</code, here's how you can do it:</p>

<pre><code>import { array } from 'fp-ts/lib/Array';
import { io } from 'fp-ts/lib/IO';

const rows: Array<...> = ...;
// regular map
const mapped: Array<IO<...>> = rows.map(attrIO('data-test'));
// equivalent to above with fp-ts functionality
const mappedFpTs: Array<IO<...>> = array.map(rows, attrIO('data-test')); 

// leveraging traverse instead of map to align `IO` with `Array` in the type signature
const result: IO<Array<...>> = array.traverse(io)(rows, attrIO('data-test'));

Finally, let's put everything together:

import { array } from 'fp-ts/lib/Array';
import { io } from 'fp-ts/lib/IO';
import { flow } from 'fp-ts/lib/function';

const getIO = selection => IO.of(selection.get())
const findIO = (...args) => selection => IO.of(selection.find(...args))
const attrIO = (...args) => element => IO.of(element.attr(...args))

const getTests = (text: string) => {
  const $ = cheerio.load(text);
  return pipe(
    $('table tr'),
    getIO,
    IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
    IO.chain(links => array.traverse(io)(links, flow(
      attrIO('data-test'), 
      IO.map(a => a ? a : null)
    ))),
    IO.map(links => links.filter(v => v != null))
  );
}

With the updated getTests, you receive back an IO containing the same elements from your initial tests variable.

EDIT:

If you wish to retain error information, such as missing data-test attributes on certain a elements, there are several approaches available. Currently, getTests yields an IO<string[]>. To accommodate error details, consider the following options:

  • IO<Either<Error, string>[]>
    - an IO returning an array where each element signifies either an error or a value. This approach maintains maximum flexibility but may seem redundant since Either<Error, string> is akin to string | null in this context.
import * as Either from 'fp-ts/lib/Either';

const attrIO = (...args) => element: IO<Either<Error, string>> => IO.of(Either.fromNullable(new Error("not found"))(element.attr(...args) ? element.attr(...args): null));

const getTests = (text: string): IO<Either<Error, string>[]> => {
  const $ = cheerio.load(text);
  return pipe(
    $('table tr'),
    getIO,
    IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
    IO.chain(links => array.traverse(io)(links, attrIO('data-test')))
  );
}
  • IOEither<Error, string[]> - an IO delivering either an error or an array of values. Typically, errors are returned upon encountering the first missing attribute, failing to capture other errors or valid values beyond that point.
import * as Either from 'fp-ts/lib/Either';
import * as IOEither from 'fp-ts/lib/IOEither';

const { ioEither } = IOEither;

const attrIOEither = (...args) => element: IOEither<Error, string> => IOEither.fromEither(Either.fromNullable(new Error("not found"))(element.attr(...args) ? element.attr(...args): null));

const getTests = (text: string): IOEither<Error, string[]> => {
  const $ = cheerio.load(text);
  return pipe(
    $('table tr'),
    getIO,
    IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
    IOEither.rightIO, // "lift" IO to IOEither context
    IOEither.chain(links => array.traverse(ioEither)(links, attrIOEither('data-test')))
  );
}
  • IOEither<Error[], string[]>
    - an IO providing either an array of errors or an array of values. This method aggregates errors while preserving multiple value results. Nevertheless, in the presence of errors, correct values remain undocumented.

This technique, although less common, proves intricate to implement and primarily suitable for validation checks. A possible solution involves employing a monad transformer like . More insights on its practical implications could shed light on better use cases.

  • IO<{ errors: Error[], values: string[] }>
    - an IO outcome comprising both error logs and value arrays. While comprehensive, this scenario poses challenges regarding implementation complexity.

A recommended practice involves defining a monoid instance for the resultant object

{ errors: Error[], values: string[] }
and subsequent utilization of foldMap to combine outcomes:

import { Monoid } from 'fp-ts/lib/Monoid';

type Result = { errors: Error[], values: string[] };

const resultMonoid: Monoid<Result> = {
  empty: {
    errors: [],
    values: []
  },
  concat(a, b) {
    return {
      errors: [].concat(a.errors, b.errors),
      values: [].concat(a.values, b.values)
    };
  } 
};

const attrIO = (...args) => element: IO<Result> => {
  const value = element.attr(...args);
  if (value) {
    return {
      errors: [],
      values: [value]
    };
  } else {
    return {
      errors: [new Error('not found')],
      values: []
  };
};

const getTests = (text: string): IO<Result> => {
  const $ = cheerio.load(text);
  return pipe(
    $('table tr'),
    getIO,
    IO.chain(rows => array.traverse(io)(rows, flow($, findIO('a')))),
    IO.chain(links => array.traverse(io)(links, attrIO('data-test'))),
    IO.map(results => array.foldMap(resultMonoid)(results, x => x))
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the generic type parameter of an interface implementation

I am attempting to extract a type parameter from an interface in order to use it as a parameter for a generic function. In my particular scenario, I have the following generic types: interface ITranslatable<T, K extends keyof T> { translations: IT ...

Circular function reference in Typescript occurs when a function calls itself

The functionality of this code snippet is rather straightforward; it either returns a function or a string based on an inner function parameter. function strBuilder(str: string) { return function next(str2?: string) { if(typeof str2 === "string& ...

Implement an interface with a specific number of properties in TypeScript

I am attempting to create a custom type that defines an object with a specific number of key-value pairs, where both the key and value are required to be numbers. Here is what I envision: type MatchResult = { [key: number]: number; [key: number]: numbe ...

Encountering an error when trying to set data in a Firestore document with a customized JavaScript object: "Invalid data provided for function DocumentReference.set()"

For my initial project, I need help in identifying where the issue lies. Firstly, I have a function that adds data to Firebase: addpost() { let newposts = new Posts( this.addForm.value ) this.postsservice.addPosts(newposts); } Ne ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...

problem encountered while attempting to drag and drop list elements on a web application utilizing dhtmlx 5.0 and wijmo grid

My web application utilizes Dhtmlx 5.0, Wijmo grid, and Typescript. One feature of the app is a dialog box that displays a list of items which can be rearranged using drag and drop functionality. This feature works without any issues on Windows PCs but enc ...

Observable doesn't respond to lazy loaded module subscriptions

I am trying to understand why my lazy loaded module, which loads the test component, does not allow the test component to subscribe to an observable injected by a test service. index.ts export { TestComponent } from './test.component'; export { ...

Exploring nested objects within an instance

I'm facing an issue with accessing a variable object within my main object. I am able to access 'start', 'end', and 'category' without any problem, but I am unsure how to access the variable Object in my Angular web app d ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

There were issues with React's compilation when integrating with antd UI

Whenever I try to compile, errors keep showing up even though I have imported from antd. I can't figure out what the problem is. These are the errors I encounter while compiling: Compiled with problems: ERROR in ./src/components/excelPage.js 130:85- ...

Comparison: executing an immediately invoked function expression (IIFE) and a separate

During my recent refactoring of some legacy code, I stumbled upon the following example: // within another function const isTriggerValid = await (async () => { try { const triggers = await db.any(getTriggerBeforeBook, { param ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises ...

Loading Angular page

I'm currently working on a personal project in Angular and I have a requirement to display a specific page for a brief period of time when the site is loaded, before redirecting to the home component. Is there a way to achieve this or create a loading ...

Having trouble adjusting the appearance of the dropdown menu in Angular Material's Select component

I've been attempting to adjust the style of the overlay panel within an Angular Material's MdSelect component in order to change the default max-width property of 280px. I have tried various methods, such as using '!important' to overr ...

The property of the Angular Typescript object is distinctly not defined, yet the property itself is

Currently facing a bizarre issue. Even though the console displays data in an object from a subscribed observable, TypeScript code shows it as undefined. Take a look: initData(): void { this.backendService.getData().subscribe((depotDays: DepotDayAcc ...

Working with TypeScript to set a value for an object's field

I have two objects of the same model: interface Project { _id?: string title: string description: string goal: string tasks?: Task[] createdAt?: Date updatedAt?: Date } The first object contains all fields from the interface, while the secon ...

Subscription to Observable content failed to run

When a submit button is clicked inside the component HTML, it triggers a function called addCollaborators(). The code for this function can be found below: component.ts emails: string[] = []; constructor(public userService: UserService) {} // Function ...

Navigating within components using code is an essential skill when working with Vue Router

I am currently developing a Quasar application powered by Vue 3 with vue-router version 4 All my routes are properly configured and function well when navigating from a component template using <router-link to="/route">Go to route</rout ...

Obtaining a binary value in the switch component of materialize framework with Typescript

Is there a way in Typescript to assign a value of 1 when a checkbox is checked and 0 otherwise? I am working on a project that uses the materialize framework. Below is the code snippet in question: <div class='switch'> <label&g ...

Having trouble accessing the database in Angular and Ionic through a provider on a Tabbed page

I created a Home page with tabs using Ionic 3 and Angular. The tabs are named Stats and Calc. When clicking on the Stats tab, it triggers the class/component stats.ts (displayed below). This component utilizes two providers: CropProvider and ContractProvi ...