Skip to content

Commit

Permalink
Merge branch 'fix/undefined-as-operation-result' into release/0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
etki committed Mar 29, 2018
2 parents baf50d9 + 62e0582 commit 9051c24
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 6 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [0.1.2] - 2018-03-29
### Fixed

- Undefined leakage as identity from operation provided to #map().

## [0.1.1] - 2018-03-24
### Fixed

Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "@ama-team/optional",
"version": "0.1.1",
"version": "0.1.2",
"main": "dist/index.js",
"repository": "git@github.com:ama-team/ts-optional.git",
"author": "AMA Team <dev@amagroup.ru>",
Expand Down
13 changes: 8 additions & 5 deletions src/Optional.ts
Expand Up @@ -32,7 +32,10 @@ export class Optional<T> implements IOptional<T> {
}

public map<V>(operation: (identity: T) => V | null): Optional<V> {
return new Optional(this.identity !== null ? operation(this.identity) : null);
if (this.identity === null) {
return Optional.empty();
}
return Optional.ofNullable(operation(this.identity));
}

public flatMap<V>(transformer: (identity: T) => IOptional<V>): Optional<V> {
Expand All @@ -52,11 +55,11 @@ export class Optional<T> implements IOptional<T> {
return this;
}

public ifEmpty(action: () => void): IOptional<T> {
public ifEmpty(action: () => void): Optional<T> {
if (this.identity === null) {
action();
}
return this as IOptional<T>;
return this;
}

public peek(consumer: (identity: (T | null)) => void): Optional<T> {
Expand Down Expand Up @@ -84,14 +87,14 @@ export class Optional<T> implements IOptional<T> {
if (this.identity !== null) {
return this;
}
return new Optional<T>(value);
return Optional.ofNullable(value);
}

public rescueWith(producer: () => T): Optional<T> {
if (this.identity !== null) {
return this;
}
return new Optional<T>(producer());
return Optional.ofNullable(producer());
}

public orElse(fallback: T): T {
Expand Down
8 changes: 8 additions & 0 deletions test/unit/Optional.spec.ts
Expand Up @@ -198,6 +198,14 @@ describe('/Optional.ts', () => {
Optional.empty().map(transformer);
expect(transformer.callCount).to.eq(0);
});

it('handles undefined result correctly', () => {
const transformer = Sinon.stub().returns(undefined);
const inspected = Optional.of(42).map(transformer);
expect(inspected.empty).to.eq(true);
expect(inspected.present).to.eq(false);
expect(() => inspected.get()).to.throw(TypeError);
});
});

describe('#flatMap', () => {
Expand Down

0 comments on commit 9051c24

Please sign in to comment.