Fp-ts: array every

Created on 10 Nov 2020  路  4Comments  路  Source: gcanti/fp-ts

馃殌 Feature request

Like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

Or does fp-ts provide an alternative way?

Most helpful comment

Hey @steida - you could use Array.foldMap to first map the values of the array to a boolean and then fold them together with an appropriate Monoid. See below.

import * as Ord from "fp-ts/Ord";
import * as M from "fp-ts/Monoid";
import * as RA from "fp-ts/ReadonlyArray";
import { pipe } from "fp-ts/function";

const isBelowThreshold = (threshold: number) => (value: number) =>
  Ord.lt(Ord.ordNumber)(value, threshold);

console.log(
  pipe(
    [1, 30, 39, 29, 10, 13], 
    RA.foldMap(M.monoidAll)(isBelowThreshold(40))
  )
);
// => true

All 4 comments

There's fp-ts-std/Array::all, but I'm curious if there's a clever way of doing this with fp-ts proper that I've missed.

Hey @steida - you could use Array.foldMap to first map the values of the array to a boolean and then fold them together with an appropriate Monoid. See below.

import * as Ord from "fp-ts/Ord";
import * as M from "fp-ts/Monoid";
import * as RA from "fp-ts/ReadonlyArray";
import { pipe } from "fp-ts/function";

const isBelowThreshold = (threshold: number) => (value: number) =>
  Ord.lt(Ord.ordNumber)(value, threshold);

console.log(
  pipe(
    [1, 30, 39, 29, 10, 13], 
    RA.foldMap(M.monoidAll)(isBelowThreshold(40))
  )
);
// => true

@IMax153 Thank you.

With modern fp-ts imports.

import { array, monoid, ord } from 'fp-ts';
import { pipe } from 'fp-ts/function';

const isBelowThreshold = (threshold: number) => (value: number) =>
  ord.lt(ord.ordNumber)(value, threshold);

// => true
console.log(
  pipe(
    [1, 30, 39, 29, 10, 13],
    array.foldMap(monoid.monoidAll)(isBelowThreshold(40)),
  ),
);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jollytoad picture jollytoad  路  4Comments

miguelferraro picture miguelferraro  路  3Comments

mmkal picture mmkal  路  3Comments

maciejsikora picture maciejsikora  路  3Comments

steida picture steida  路  4Comments