typescript-optional icon indicating copy to clipboard operation
typescript-optional copied to clipboard

Map should be applied only if payload is present

Open stonedMoose opened this issue 4 years ago • 0 comments

I think map should be applied only if payload is present.

It gives us the ability to chain map method whether the paylaod is present or not.

If you look at the java implementation, it is implemented that way.

    public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent()) {
            return empty();
        } else {
            return Optional.ofNullable(mapper.apply(value));
        }
    }

The current implementation force the developer to null-check value in the mapper. It seems kind of counter intuitive to me.

// currently I do this
  this.phone = Optional.ofNullable(builder.phone).map((phone) => {
    if (phone) {
      Assert.isValidPhoneNumber(builder.phone);
      return new Name(phone);
    }
    return undefined;
  });

// while it could simply be 
  this.phone = Optional.ofNullable(builder.phone).map((phone) => {
      Assert.isValidPhoneNumber(builder.phone);
      return new Name(phone);
    }  });

I could suggest a PR if you're willing to accept this change.

stonedMoose avatar Aug 30 '21 12:08 stonedMoose