All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.effect.util.PureRandom Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2022, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.effect.util;

import static com.github.tonivade.purefun.Precondition.checkNonNull;
import static java.util.stream.Collectors.joining;

import java.util.Random;
import java.util.stream.IntStream;

import com.github.tonivade.purefun.effect.URIO;

public interface PureRandom {

   PureRandom.Service random();

  static  URIO nextInt() {
    return URIO.accessM(env -> env.random().nextInt());
  }

  static  URIO nextLong() {
    return URIO.accessM(env -> env.random().nextLong());
  }

  static  URIO nextFloat() {
    return URIO.accessM(env -> env.random().nextFloat());
  }

  static  URIO nextDouble() {
    return URIO.accessM(env -> env.random().nextDouble());
  }

  static  URIO nextChar() {
    return URIO.accessM(env -> env.random().nextChar());
  }

  static  URIO nextString(int length) {
    return URIO.accessM(env -> env.random().nextString(length));
  }

  interface Service {
    URIO nextInt();
    URIO nextLong();
    URIO nextFloat();
    URIO nextDouble();
    URIO nextChar();
    URIO nextString(int length);
  }

  static PureRandom live() {
    return new PureRandomImpl(new Random());
  }

  static PureRandom test(long seed) {
    return new PureRandomImpl(new Random(seed));
  }
}

class PureRandomImpl implements PureRandom {

  private static final String PRINTABLE_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  private final Random random;

  PureRandomImpl(Random random) {
    this.random = checkNonNull(random);
  }

  @Override
  public  PureRandom.Service random() {
    return new PureRandom.Service() {

      @Override
      public URIO nextInt() {
        return URIO.task(random::nextInt);
      }

      @Override
      public URIO nextLong() {
        return URIO.task(random::nextLong);
      }

      @Override
      public URIO nextFloat() {
        return URIO.task(random::nextFloat);
      }

      @Override
      public URIO nextDouble() {
        return URIO.task(random::nextDouble);
      }

      @Override
      public URIO nextChar() {
        return URIO.task(this::randomChar);
      }

      @Override
      public URIO nextString(int length) {
        return URIO.task(() -> randomString(length));
      }

      private Character randomChar() {
        return PRINTABLE_CHARS.charAt(random.nextInt(PRINTABLE_CHARS.length()));
      }

      private String randomString(int length) {
        return IntStream.range(0, length).mapToObj(x -> randomChar()).map(Object::toString).collect(joining());
      }
    };
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy