Skip to content

Commit

Permalink
Merge pull request #65 from funkia/first-and-last-affix-sizes
Browse files Browse the repository at this point in the history
first and last correctly uses affix sizes
  • Loading branch information
paldepind committed Sep 2, 2018
2 parents 1e315e1 + 9f95964 commit b40eb2c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -870,11 +870,12 @@ export function length(l: List<any>): number {
* first(list()); //=> undefined
*/
export function first<A>(l: List<A>): A | undefined {
if (getPrefixSize(l) !== 0) {
return arrayLast(l.prefix);
} else if (getSuffixSize(l) !== 0) {
return arrayFirst(l.suffix);
}
const prefixSize = getPrefixSize(l);
return prefixSize !== 0
? l.prefix[prefixSize - 1]
: l.length !== 0
? l.suffix[0]
: undefined;
}

/**
Expand All @@ -888,11 +889,12 @@ export function first<A>(l: List<A>): A | undefined {
* last(list()); //=> undefined
*/
export function last<A>(l: List<A>): A | undefined {
if (getSuffixSize(l) !== 0) {
return arrayLast(l.suffix);
} else if (getPrefixSize(l) !== 0) {
return arrayFirst(l.prefix);
}
const suffixSize = getSuffixSize(l);
return suffixSize !== 0
? l.suffix[suffixSize - 1]
: l.length !== 0
? l.prefix[0]
: undefined;
}

// map
Expand Down
10 changes: 10 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,11 @@ describe("List", () => {
assert.strictEqual(first(list()), undefined);
assert.strictEqual(last(list()), undefined);
});
it("returns the first element based on prefix size", () => {
const l = L.prepend(0, L.empty());
L.prepend(1, l);
assert.strictEqual(L.first(l), 0);
});
it("gets the last element of prepended list", () => {
const l = prepend(0, prepend(1, prepend(2, empty())));
assert.strictEqual(last(l), 2);
Expand All @@ -419,6 +424,11 @@ describe("List", () => {
it("can get the first element when suffix overflows", () => {
assert.strictEqual(first(appendList(0, 33)), 0);
});
it("returns the last element based on suffix size", () => {
const l = L.append(0, L.empty());
L.append(1, l);
assert.strictEqual(L.last(l), 0);
});
});
describe("concat", () => {
check("has left identity", genList, l => {
Expand Down

0 comments on commit b40eb2c

Please sign in to comment.