Skip to content

Instantly share code, notes, and snippets.

@Mattamorphic
Created February 5, 2026 10:28
Show Gist options
  • Select an option

  • Save Mattamorphic/0e29a97dffe51e07340b1a4095ecba92 to your computer and use it in GitHub Desktop.

Select an option

Save Mattamorphic/0e29a97dffe51e07340b1a4095ecba92 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
/**
* Usage:
* export OPENAI_API_KEY="..."
* node leftpad-via-chatgpt.js "hello" 12 "*"
*
* Args:
* 1) input string (default: "hello")
* 2) target width (default: 10)
* 3) pad char (default: " ")
*/
const input = process.argv[2] ?? "hello";
const width = Number(process.argv[3] ?? 10);
const padChar = (process.argv[4] ?? " ").toString();
if (!Number.isFinite(width) || width < 0) {
console.error("Width must be a non-negative number.");
process.exit(1);
}
if (padChar.length === 0) {
console.error("Pad char must be at least 1 character.");
process.exit(1);
}
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
console.error("Missing OPENAI_API_KEY env var.");
process.exit(1);
}
async function main() {
const prompt = [
"You are a helpful coding agent.",
"Left-pad the given string to the target width using the pad character.",
"Return ONLY the final padded string. No quotes. No explanation.",
`input=${JSON.stringify(input)}`,
`width=${width}`,
`padChar=${JSON.stringify(padChar)}`,
].join("\n");
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
temperature: 0,
}),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
}
const data = await res.json();
const out = data.choices?.[0]?.message?.content ?? "";
process.stdout.write(out.trimEnd() + "\n");
}
main().catch((err) => {
console.error(err?.stack || String(err));
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment