Effect CommunityEC
Effect Community3y ago
78 replies
Yaoquizque

Appreciation for Great Tools and Learning Journey in Effect

Hello!

First of, let me take this opportunity to thank you lads for making such great tools available for everyone
I started getting into Effect since a few weeks and I'm having great times so far. Still have a long way to go though.

For example, I used to write a function that was basically a while loop to accumulate values in an array:

let match = null;
const result = [];

while (null !== (match = depsRegex.exec(input))) {
  const dep = match[2];

  if (!dep.startsWith('./') && !dep.startsWith('../')) {
    result.push(dep);
  }
}


My mentor @Kadelka suggested I could use Effect.loop to do just that, so here we go:

const getExternalImports = (fileContent: string) =>
  pipe(
    Effect.sync(() => depsRegex.exec(fileContent)),
    Effect.flatMap((firstMatch) =>
      Effect.loop(firstMatch, {
        step: () => depsRegex.exec(fileContent),
        while: (newMatch) => newMatch !== null,
        body: (match) => {
          if (!match) {
            return Effect.succeed(null);
          }

          const dep = match[2];
          if (!dep.startsWith('./') && !dep.startsWith('../')) {
            return Effect.succeed(dep);
          }

          return Effect.succeed(null);
        },
      }),
    ),
    Effect.map((imports) => imports.filter((i) => i !== null) as string[]),
  );


I'm not satisfied with this function though. I still need to do a map in the end to remove null values. I tried replacing Effect.succeed(null) with Effect.fail('no match' as const) for example so that I can then discard these errors to only keep the array, but I don't think it's really nice either. I also tried Effect.never but the effect never resolves. Effect.unit does not seem to answer my need either, as the return type of body would be Effect<never, never, void>

What would be the best way to write this elegantly? a gen function to be able to use the break keyword? Or is there some magic I'm missing?
Was this page helpful?