Skip to content

Commit

Permalink
More functions (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
raviqqe committed Nov 10, 2023
1 parent 40df225 commit 520b1f1
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/identity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const identity = <T>(x: T): T => x;
13 changes: 13 additions & 0 deletions src/last.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { it, expect } from "vitest";
import { last } from "./last.js";

for (const [xs, y] of [
[[], undefined],
[[1], 1],
[[1, 2], 2],
[[1, 2, 3], 3],
] satisfies [unknown[], unknown][]) {
it(`finds the last element in an array ${JSON.stringify(xs)}`, () => {
expect(last(xs)).toBe(y);
});
}
3 changes: 3 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export * from "./identity.js";
export * from "./last.js";
export * from "./once.js";
export * from "./unique.js";
17 changes: 17 additions & 0 deletions src/once.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { it, expect } from "vitest";
import { once } from "./once.js";

it("calls a function twice", () => {
let x = 0;
const f = once(() => {
x++;
});

f();

expect(x).toBe(1);

f();

expect(x).toBe(1);
});
15 changes: 15 additions & 0 deletions src/once.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const once = <T extends unknown[], S>(
f: (...args: T) => S,
): ((...args: T) => S) => {
let called = false;
let value: S;

return (...args: T): S => {
if (!called) {
called = true;
value = f(...args);
}

return value;
};
};

0 comments on commit 520b1f1

Please sign in to comment.