When it comes to
Take, for instance, a function that copies text to the clipboard. It might seem straightforward, but there are multiple aspects to consider: What if the
To address these questions, I embarked on a journey to craft a copyTextToClipboard
function that could stand the test of real-world applications. I had an AI partner on this journey:
So why choose this particular function? While I haven't encountered issues with existing Copy To Clipboard functions, the goal was to create one that not only functions effectively but is also built according to the latest JS standards and best practices.
Here's what we developed (Note:
/**
* Copies the provided text to the clipboard.
*
* @param {string} text - The text to be copied to the clipboard.
* @returns {Promise} A promise that resolves when the text has been successfully copied, or rejects when an error occurs or the Clipboard API is not supported.
*/
const copyTextToClipboard = (text) => {
return new Promise((resolve, reject) => {
// Check if the text is a string and not empty.
if (typeof text !== "string" || text.trim() === "") {
reject(new Error("Invalid text: Text should be a non-empty string."));
return;
}
// Check if the Clipboard API is supported.
if (!navigator.clipboard) {
reject(new Error("Clipboard API not supported"));
return;
}
// Try to write the text to the clipboard.
navigator.clipboard
.writeText(text)
.then(resolve) // If successful, resolve the promise.
.catch(reject); // If an error occurs, reject the promise with the error.
});
};
So, why should you consider using this function over others? Here are some key reasons:
const
for function declaration,
Working with GPT on this was quite an experience. I learned the hard way that it's essential to define GPT's persona and provide as much context as possible-the more precise and specific the instructions, the more satisfactory and applicable the results.
Act as a JavaScript Developer using the latest stable ECMA Script standards that are supported on modern browsers. You only write robust, reusable, readable, well-documented, performant, and secure code that conforms to best practices for production environments. Perform a code review of the following JavaScript function and if it fails your standards and practices, rewrite it with explanations of what you changed and why:
I then pasted a version of
copyTextToClipboard
that I felt was quite good.
In response, GPT not only followed my instructions but also added additional value, enhancing readability, reusability, and error handling in the function. The collaboration resulted in a piece of code I was happy to add to my project.
It's important to understand the caveats when working with a function like this:
As we continue to adopt AI tools like
Feel free to use this function in your projects and, more importantly, reference
Till next time - John 🙂