Skip to content

Commit

Permalink
Merge pull request #136 from dolthub/taylor/sprintf
Browse files Browse the repository at this point in the history
utils: Add sprintf
  • Loading branch information
tbantle22 committed Jun 12, 2024
2 parents 308dfdb + 6f4fdaa commit fe1cab2
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
59 changes: 59 additions & 0 deletions packages/utils/src/__tests__/sprintf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { sprintf } from "../sprintf";

describe("test sprintf", () => {
it("should replace single $ with provided argument", () => {
const result = sprintf("Hello, $!", "world");
expect(result).toBe("Hello, world!");
});

it("should replace multiple $ with corresponding arguments", () => {
const result = sprintf(
"$ is $, and $ is $",
"This",
"a test",
"this",
"a test",
);
expect(result).toBe("This is a test, and this is a test");
});

it("should handle no replacements if no $ in string", () => {
const result = sprintf("No placeholders here.");
expect(result).toBe("No placeholders here.");
});

it("should handle no arguments provided", () => {
const result = sprintf("Hello, $!");
expect(result).toBe("Hello, $!");
});

it("should handle extra arguments provided", () => {
const result = sprintf("Hello, $!", "world", "extra");
expect(result).toBe("Hello, world!");
});

it("should handle fewer arguments than placeholders", () => {
const result = sprintf("Hello, $ and $!", "world");
expect(result).toBe("Hello, world and $!");
});

it("should replace multiple $ with numbers", () => {
const result = sprintf("$ + $ = $", 1, 2, 3);
expect(result).toBe("1 + 2 = 3");
});

it("should replace multiple $ with mixed types", () => {
const result = sprintf("$ is $ and $ is $", "1", 2, true, "false");
expect(result).toBe("1 is 2 and true is false");
});

it("should replace $ with empty string if provided as an argument", () => {
const result = sprintf("Hello, $!", "");
expect(result).toBe("Hello, !");
});

it("should handle null and undefined as arguments", () => {
const result = sprintf("Hello, $ and $!", null, undefined);
expect(result).toBe("Hello, null and undefined!");
});
});
8 changes: 8 additions & 0 deletions packages/utils/src/sprintf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const replaceToken = "$";

// sprintf takes a string and replaces all instances of `replaceToken` with the provided arguments
export const sprintf = (str: string, ...argv: any[]): string => {
if (!argv.length) return str;
// eslint-disable-next-line no-return-assign, no-param-reassign
return sprintf((str = str.replace(replaceToken, argv.shift())), ...argv);
};

0 comments on commit fe1cab2

Please sign in to comment.