How ChatGPT Can Be Used in Coding?

ChatGPT has gained a lot of popularity for its ability to answer questions and generate human-like responses. However, its potential in the field of coding is often underestimated.

ChatGPT has the potential to revolutionize the way developers approach coding. The platform offers an array of solutions to various coding problems that developers face on a daily basis.

It can be used to generate code for a variety of programming languages, such as HTML, JavaScript, Python, and more.

We at Bitkraft experimented to see how ChatGPT can be used in coding, and this post is about our findings.

Experiment 1: Developing HTML5 Components

One of the most common tasks in web development is to create an HTML5 component. In this regard, ChatGPT can be used to generate HTML, JavaScript, and CSS for components that are normally hard to create – such as an image slider – within a few seconds.

When we asked ChatGPT to create an HTML page for showing an image slider, it delivered a production-ready Image Slider code snippet which any serious frontend developer would have been proud of!

The Prompt

Here is the prompt we gave ChatGPT…

Create an HTML5 based image slider component which transforms a regular list with image tags in it, into a carousel. The carousel should be able to display 1, 2,3 or 4 images at a time. The code should use vanilla javascript and jQuery only. Animations must be handled via CSS - no inline CSS to be used. The slider should have next and back buttons on the sides of the slider. The number of images visible should be configurable.

ChatGPT Generated Code

<!DOCTYPE html>
<html>
<head>
  <style>
    .slider {
      width: 100%;
      overflow: hidden;
      position: relative;
    }

    .slider ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      display: flex;
      transition: transform 0.5s ease;
    }

    .slider li {
      flex: 0 0 25%;
    }

    .slider img {
      width: 100%;
      height: auto;
    }

    .slider .prev,
    .slider .next {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      background-color: rgba(0, 0, 0, 0.3);
      color: #fff;
      padding: 10px;
      font-size: 24px;
      cursor: pointer;
    }

    .slider .prev {
      left: 0;
    }

    .slider .next {
      right: 0;
    }
  </style>
</head>
<body>
  <div class="slider">
    <ul>
      <li><img src="" alt="Image 1"></li>
      <li><img src="" alt="Image 2"></li>
      <li><img src="" alt="Image 3"></li>
      <li><img src="" alt="Image 4"></li>
      <li><img src="" alt="Image 5"></li>
      <li><img src="" alt="Image 6"></li>
    </ul>
    <div class="prev">&lt;</div>
    <div class="next">&gt;</div>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      var slider = $('.slider');
      var sliderUl = slider.find('ul');
      var sliderItems = sliderUl.find('li');
      var sliderCount = sliderItems.length;
      var visibleItemCount = 4; // Change this value to configure the number of visible images

      // Calculate the width of each slider item based on the number of visible items
      var itemWidth = 100 / visibleItemCount + '%';
      sliderItems.css('flex-basis', itemWidth);

      // Set the width of the slider ul based on the number of items
      var sliderUlWidth = sliderCount * (100 / visibleItemCount) + '%';
      sliderUl.css('width', sliderUlWidth);

      // Initialize the current slide index
      var currentSlide = 0;

      // Handle previous button click event
      $('.prev').click(function() {
        if (currentSlide > 0) {
          currentSlide--;
          moveSlider();
        }
      });

      // Handle next button click event
      $('.next').click(function() {
        if (currentSlide < sliderCount - visibleItemCount) {
          currentSlide++;
          moveSlider();
        }
      });

      // Move the slider to the current slide
      function moveSlider() {
        var translateX = -(currentSlide * 100 / visibleItemCount) + '%';
        sliderUl.css('transform', 'translateX(' + translateX + ')');
      }
    });
  </script>
</body>
</html>

ChatGPT Generated Image Slider in Action!

  • Image 1
  • Image 2
  • Image 3
  • Image 4
  • Image 5
  • Image 6

Experiment 2: Performance Testing for APIs

Performance testing is crucial for ensuring that APIs can handle heavy traffic and perform well under different scenarios.

ChatGpt can be used to generate guidelines and steps for performance testing. When asked to suggest guidelines and steps for performance testing for APIs, ChatGpt provided an accurate response.

The Prompt

provide a sample script for locust

ChatGPT Generated Code

from locust import HttpUser, TaskSet, task, between

class UserBehavior(TaskSet):
    @task
    def get_homepage(self):
        self.client.get("/")

class WebsiteUser(HttpUser):
    tasks = [UserBehavior]
    wait_time = between(5, 9)  # Wait time between consecutive tasks in seconds

    def on_start(self):
        self.client.verify = False  # Disable SSL certificate verification

To run this script, you need to have Locust installed. Once installed, save the script to a file (e.g., load_test.py), and then you can start Locust from the command line with the following command:

locust -f load_test.py

The provided script is used to run single locust py file. To run multiple locust py files we asked ChatGPT to provide a solution.

The Prompt

what if i want to run multiple locust py files. how can i do that?

ChatGPT Generated Response

  1. Save your Locust scripts in separate files, for example load_test1.py and load_test2.py.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where your Locust script files are located.
  4. Execute the following command to start Locust and run multiple scripts simultaneously:.
locust -f load_test1.py -f load_test2.py

After executing the command, Locust will start and run all the specified scripts concurrently. Each script will run in its own worker process, simulating the load defined in each script.

This is the statistical data of the API's request and its performance.

  • Response time chart: This chart shows the average response time for all requests made during the test. This can be used to see how long it takes for the API to respond to requests.
  • RPS (Requests per second) chart: This chart shows the number of requests made per second during the test. This can be used to see how much load the API can handle.

Experiment 3: Reading Large CSV Files

Reading large CSV files can be a challenging task for developers. However, ChatGPT can help by providing the fastest way to read large CSV files.

When we asked ChatGPT to write a Python script to read a very large CSV file, it not only provided the script but also gave sample data. The generated code worked faster compared to any other method of reading large CSV files.

The prompt

write a python script to read very large csv file. this file contains user id and data info based on date range. we need to find the count of users between certain date range. e.g. if the difference between current date and column date value is 90 days than group of 90 days. user should be created and get the count of it.

Below is an example of a Python script that reads a large CSV file and counts the number of users within a specified date range:

ChatGPT Generated Code

pythonCopy codeimport csv
from datetime import datetime, timedelta

def count_users_in_date_range(csv_file, start_date, end_date, group_days):
user_counts = {}
current_group_start = start_date
current_group_end = current_group_start + timedelta(days=group_days)

with open(csv_file, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row

for row in reader:
user_id = row[0]
date_str = row[1]
date = datetime.strptime(date_str, "%Y-%m-%d")

if date < start_date or date > end_date:
continue

if date > current_group_end:
current_group_start = date
current_group_end = current_group_start + timedelta(days=group_days)

current_group = (current_group_start, current_group_end)
user_counts[current_group] = user_counts.get(current_group, 0) + 1

return user_counts

# Example usage
csv_file = 'large_file.csv'
start_date = datetime(2023, 1, 1)
end_date = datetime(2023, 12, 31)
group_days = 90

result = count_users_in_date_range(csv_file, start_date, end_date, group_days)

for group, count in result.items():
print(f"Group {group}: {count} users")

In the script, you need to provide the path to your CSV file (csv_file) and specify the start_date, end_date, and group_days according to your requirements.

The script reads the CSV file row by row, checks if the date falls within the specified range, and groups users based on the given group_days value.

The resulting user counts are stored in a dictionary where the key represents the group (start and end date) and the value is the count of users in that group. The script then prints the user counts for each group.

This is a CSV File data we used to test the code.

data = [
    ("1", "2023-01-05"),
    ("2", "2023-02-15"),
    ("3", "2023-03-20"),
    ("4", "2023-04-01"),
    ("5", "2023-05-10"),
    ("6", "2023-06-30"),
    ("7", "2023-07-12"),
    ("8", "2023-08-25"),
    ("9", "2023-09-02"),
    ("10", "2023-10-18"),
    ("11", "2023-11-30"),
    ("12", "2023-12-10")
]

This is the Output

Group (datetime.datetime(2023, 1, 1, 0, 0), datetime.datetime(2023, 4, 1, 0, 0)): 4 users
Group (datetime.datetime(2023, 5, 10, 0, 0), datetime.datetime(2023, 8, 8, 0, 0)): 3 users
Group (datetime.datetime(2023, 8, 25, 0, 0), datetime.datetime(2023, 11, 23, 0, 0)): 3 users
Group (datetime.datetime(2023, 11, 30, 0, 0), datetime.datetime(2024, 2, 28, 0, 0)): 2 users

Generated output is as per our requirements. The code provided by chatGPT fits in perfectly with our existing functionality.

Experiment 4 : Code Conversion from Python to JavaScript

Using ChatGPT in coding can be incredibly helpful in saving time by converting code from one programming language to another. Let me share a scenario where we encountered a Python code for a custom compressor logic. Our requirement was to compress a file and upload it into a system using JavaScript. Thanks to ChatGPT, we were able to convert the Python code into JavaScript effortlessly.

To ensure the consistency of the converted code, we provided the same input and compared the output of both codes. Surprisingly, the generated code seamlessly integrated into our existing codebase, delivering the desired functionality. we realized it would save the developer many working hours writing the code to achieve the same functionality.

The Prompt

Convert the Below code in javascript.

from datetime import datetime, timedelta

def reconstruct_prices(prices_str):
    reconstructed_prices_arr = []
    if prices_str != "":
        for price_data in prices_str.split(","):
            date, price, run_length = price_data.split('|')
            date_obj = datetime.strptime(date, "%Y%m%d")
            for day_interval in range(int(run_length)):
                reconstructed_prices_arr.append({
                    "date": (date_obj + timedelta(days=day_interval)).strftime("%Y%m%d"),
                    "price": price
                })
    return reconstructed_prices_arr

prices_str = input("Enter price data (format: date|price|run_length): ")

output = reconstruct_prices(prices_str)
print(output)

Input

Enter price data (format: date|price|run_length): 20220101|10.5|3,20220105|12.2|2,20220110|9.8|4

Output

[{'date': '20220101', 'price': '10.5'}, {'date': '20220102', 'price': '10.5'}, {'date': '20220103', 'price': '10.5'}, {'date': '20220105', 'price': '12.2'}, {'date': '20220106', 'price': '12.2'}, {'date': '20220110', 'price': '9.8'}, {'date': '20220111', 'price': '9.8'}, {'date': '20220112', 'price': '9.8'}, {'date': '20220113', 'price': '9.8'}]

ChatGPT Generated Code

function runLengthDecode(pricesStr) {
  const reconstructedPricesArr = [];
  if (pricesStr !== "") {
    const priceDataArr = pricesStr.split(",");
    for (const priceData of priceDataArr) {
      const [date, price, runLength] = priceData.split("|");
      const dateObj = new Date(date.slice(0, 4), parseInt(date.slice(4, 6)) - 1, date.slice(6));
      for (let dayInterval = 0; dayInterval < parseInt(runLength); dayInterval++) {
        const currentDate = new Date(dateObj.getTime() + dayInterval * 24 * 60 * 60 * 1000);
        const formattedDate = currentDate.toISOString().slice(0, 10).replace(/-/g, "");
        reconstructedPricesArr.push({ "date": formattedDate, "price": price });
      }
    }
  }
  return reconstructedPricesArr;
}

You can test the above Javascript code by using the same input provided for Python code and compare the output.

Reconstructed Prices

Reconstructed Prices


Output:





Experiment 5 : Generating Nested Tree Dictionary Object

In the scenario where we needed to convert a folder path into a nested tree dictionary object, ChatGPT provided a quick and efficient solution.

In the example above, ChatGPT was requested to update the code to handle recursion for any length of path, and it delivered a recursion version of the function.

The Prompt

Write a python function to convert path e.g. /a/b/c to nested tree dictionary object.

ChatGPT Generated Code

def convert_path_to_tree(path):
    tree = {}
    paths = path.strip("/").split("/")
    current_node = tree

    for path in paths:
        current_node[path] = {}
        current_node = current_node[path]

    return tree

This function takes a "path" string as input and initializes an empty "tree" dictionary. It then splits the "path" string by the "/" delimiter to get a list of path components.

Here's an example usage of the function:

path = "/a/b/c"
tree = convert_path_to_tree(path)
print(tree)

Output

{'a': {'b': {'c': {}}}}

Experiment 6 : Converting Date Formats

The Prompt

Write a JavaScript to convert date string 31/03/2023 to date object.

ChatGPT Generated Response

// Input date string
var dateString = "31/03/2023";

// Split the date string into day, month, and year
var parts = dateString.split("/");
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[2], 10);

// Create a new date object using the extracted day, month, and year
var dateObject = new Date(year, month - 1, day);

console.log(dateObject);

Above code works fine, but we needed to use regular expression. So we asked to update the code

Next Prompt

can you use regex instead of split

Updated Code

// Input date string
var dateString = "31/03/2023";

// Extract day, month, and year using regex
var regexPattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var matches = dateString.match(regexPattern);

// Extract values from regex matches
var day = parseInt(matches[1], 10);
var month = parseInt(matches[2], 10);
var year = parseInt(matches[3], 10);

// Create a new date object using the extracted day, month, and year
var dateObject = new Date(year, month - 1, day);

console.log(dateObject);

ChatGPT generated code for specific date format. AS per our requirements we asked to update the code with generic date format.

Our next Prompt

Can you improve above function to make it more generic which takes date format

Updated Code

function convertToDateObject(dateString, dateFormat) {
  // Escape special characters in the date format
  var escapedFormat = dateFormat.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

  // Extract day, month, and year using regex
  var regexPattern = new RegExp(escapedFormat.replace('DD', '(\\d{1,2})').replace('MM', '(\\d{1,2})').replace('YYYY', '(\\d{4})'));
  var matches = dateString.match(regexPattern);

  // Extract values from regex matches
  var dayIndex = dateFormat.indexOf('DD') + 1;
  var monthIndex = dateFormat.indexOf('MM') + 1;
  var yearIndex = dateFormat.indexOf('YYYY') + 1;

  var day = parseInt(matches[dayIndex], 10);
  var month = parseInt(matches[monthIndex], 10);
  var year = parseInt(matches[yearIndex], 10);

  // Create a new date object using the extracted day, month, and year
  var dateObject = new Date(year, month - 1, day);

  return dateObject;
}

// Example usage
var dateString = "31/03/2023";
var dateFormat = "DD/MM/YYYY";

var dateObject = convertToDateObject(dateString, dateFormat);
console.log(dateObject);

ChatGpt can be used to generate code for converting date formats. When we asked ChatGpt to convert a date from one format to another, it initially used the split method. However, when we asked to modify the response to use regex instead of split, ChatGpt modified the response and provided a custom function that perfectly fit the code.

You can test the code below as well. Here are some test cases.

Test Case:
Date String: 2023-03-31
Date Format: YYYY-MM-DD

Test Case:
Date String: 31/03/2023
Date Format: DD/MM/YYYY

Test Case:
Date String: 2023/March/31
Date Format: YYYY/MMMM/DD
Date Conversion Test

Generate date object



If you have tried the above test cases. The code provided by ChatGPT fails the third test case. Even if you ask ChatGPT to provide a working code to pass the test case, it fails every time. Even after pointing out the mistake and giving specific instructions, ChatGPT provides a code which it thinks is correct but fails to pass the test case. This shows the limitation of an AI to understand its limitations and correctness.

ChatGPT is a large language model that can generate text, translate languages, write different kinds of creative content, and answer your questions in an informative way. However, it is still under development and has some limitations. One of these limitations is that it can sometimes fail to understand its own limitations and correctness.

This shows the difference between a real developer and an AI.

Real developers have the ability to understand their own limitations and correctness. They can also identify and correct mistakes that AI systems make. This is why it is important to have real developers working alongside AI systems.

Conclusion

ChatGPT can be a great tool for developers to assist in their coding tasks. It can provide solutions to complex problems, generate code for various programming languages, and offer suggestions to improve the code's quality.

ChatGPT offers optimized and accurate code that is specific to the developer's requirements. It is able to handle exception and error scenarios. It can also save time by generating boilerplate code and writing code as per specific requirements.

With its ability to understand natural language and respond in human-like language, ChatGPT can save developers time and effort in coding.

However, it's important to note that the output quality depends on the quality of the prompts. It did require a seasoned developer to carefully write the requirements to be able to get the outcomes we did.

ChatGPT is not a substitute for a human developer, and its responses should be verified and tested before being implemented in production code.

Overall, ChatGPT can be a valuable resource for developers looking to improve their productivity and improve their code quality.

Develop Secure and Reliable Software with Bitkraft

If you’re looking to develop software that is secure and free from vulnerabilities, trust our team of experts at Bitkraft.

Contact us today to learn more about our development process and how we can help you develop software that is secure, reliable, and trusted by your customers.

Please enable JavaScript in your browser to complete this form.
Sign up for latest updates on tech, news and happenings at Bitkraft.
Share your love
Bitkraft Technologies
Bitkraft Technologies
Articles: 16