Improving Slug Generation with Effect.loop in Typescript

Hi. I have a use case where I generate a slug for a blog post, and I want it to be unique, so i generate one, i check if the slug already exist, if it does i regenerate, if not i use it. I use the Effect.loop for it but i wonder it there is a better way?
The only problem with Effect.loop I have is that it does not provide access to the previous results in the loop, so I need to keep track of them myself in previousSlugs. Also, do I need to add the item to the previousSlug in the step or body? And one more thing is that the step part does not take an Effect, so I had to use sync on it. It's not ideal...
Suggestions for improvements welcome.
    const previousSlugs: string[] = []

    yield* E.logInfo('slug exists, regenerating')
    const results = yield* E.loop(existingSlug.value as string | undefined, {
      while: (slug) => slug !== undefined,
      step: (slug) =>
        // `step` does not accept an effect
        checkSlugExists(slug).pipe(
          E.tap((slug) => E.logInfo('slug exists', slug)),
          E.map(Option.getOrUndefined),
          E.provide(BlogStore.Default),
          E.runSync,
        ),
      body: (slug) =>
        E.gen(function* () {
          previousSlugs.push(slug)
          // regenerate needs access to all previous slugs
          // and it calls Ai service thats why it's an option
          const newSlug = yield* reGenerateSlug(previousSlugs).pipe(
            E.flatten,
            E.orElseFail(
              () =>
                new BlogPostDataError({
                  message: 'Generating new slug failed',
                }),
            ),
          )

          yield* E.logInfo('new slug', newSlug.slug)
          return newSlug.slug
        }),
    }).pipe(E.tap((results) => E.logInfo('loop results', results)))

    if (results.length === 0) {
      return yield* new BlogPostDataError({
        message: 'No unique slug found',
      })
    }
Was this page helpful?