Skip to content

Commit

Permalink
feat(Maybe): add tryLast, bump to beta.4
Browse files Browse the repository at this point in the history
  • Loading branch information
seangwright committed Nov 11, 2021
1 parent e0bf5ff commit 56abbf0
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "typescript-functional-extensions",
"description": "A TypeScript implementation of https://github.com/vkhorikov/CSharpFunctionalExtensions",
"version": "1.0.0-beta.3",
"version": "1.0.0-beta.4",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
Expand Down
36 changes: 36 additions & 0 deletions src/maybe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,42 @@ export class Maybe<TValue> {
}
}

/**
* Returns a Maybe containing the last value of the array,
* and a Maybe.none if the array is empty
* @param values
*/
static tryLast<TValue>(values: TValue[]): Maybe<TValue>;
/**
* Returns a Maybe containing the value of the last element
* of the array matching the condition of the predicate, and
* a Maybe.none if there are no matches
* @param values
* @param predicate
*/
static tryLast<TValue>(
values: Some<TValue>[],
predicate: PredicateOfT<Some<TValue>>
): Maybe<TValue>;
static tryLast<TValue>(
values: Some<TValue>[],
predicate?: PredicateOfT<Some<TValue>>
): Maybe<TValue> {
if (isFunction(predicate)) {
for (let index = values.length - 1; index >= 0; index--) {
const value = values[index];

if (predicate(value)) {
return new Maybe(value);
}
}

return Maybe.none();
} else {
return new Maybe(values[values.length - 1]);
}
}

/**
* Returns only the Maybe instances of the array that have
* values
Expand Down
36 changes: 36 additions & 0 deletions test/maybe/tryLast.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Maybe } from '@/src/maybe';
describe('Maybe', () => {
describe('tryLast', () => {
test('creates a Maybe with a value when the array has a value', () => {
const items = [1, 2, 3];

const sut = Maybe.tryLast(items);

expect(sut).toHaveValue(items[2]);
});

test('creates a Maybe with no value when the array is empty', () => {
const items: number[] = [];

const sut = Maybe.tryLast(items);

expect(sut).toHaveNoValue();
});

test('creates a Maybe with the last value which matches the predicate', () => {
const items = [1, 2, 3, 4];

const sut = Maybe.tryLast(items, (i) => i > 2);

expect(sut).toHaveValue(4);
});

test('creates a Maybe with no value when the predicate has no matches', () => {
const items = [1, 2, 3, 4];

const sut = Maybe.tryLast(items, (i) => i > 10);

expect(sut).toHaveNoValue();
});
});
});

0 comments on commit 56abbf0

Please sign in to comment.