My chatGPT hacks as javascript developer

Artsiom Marozau
7 min readMar 5, 2024

--

As a software engineer with a decade of experience, I’ve been utilizing ChatGPT over the past two years to augment my coding. In this article, I aim to share strategies that have significantly boosted my productivity.

Introduce the role

Start with clearly defining the role that aligns with your coding requirement. Structure your prompt by combining the role, task, and any specific conditions or formats needed.

Examples:

write react code that will find median value from inputed to the text input

import React, { useState } from 'react';

function MedianCalculator() {
const [input, setInput] = useState('');
const [median, setMedian] = useState(null);

const handleInputChange = (event) => {
const value = event.target.value;
setInput(value);

const numbers = value.split(',').map(num => parseFloat(num.trim())).filter(num => !isNaN(num));
if (numbers.length > 0) {
setMedian(calculateMedian(numbers));
} else {
setMedian(null);
}
};

const calculateMedian = (numbers) => {
numbers.sort((a, b) => a - b);

const mid = Math.floor(numbers.length / 2);

if (numbers.length % 2 === 0) {
return (numbers[mid - 1] + numbers[mid]) / 2;
}

return numbers[mid];
};

return (
<div>
<input type="text" value={input} onChange={handleInputChange} placeholder="Enter numbers separated by commas" />
<p>Median: {median !== null ? median : 'N/A'}</p>
</div>
);
}

export default MedianCalculator;

chat link

Enhanced Prompt:

as react developer, that write typescript code, following best a11y rules, looking for best performance optimisations, write react code that will find median value from inputed to the text input

import React, { useState } from 'react';

const MedianFinder: React.FC = () => {
const [inputValue, setInputValue] = useState<string>('');
const [median, setMedian] = useState<number | null>(null);

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
};

const findMedian = () => {
const numbers = inputValue.split(',')
.map(num => parseFloat(num.trim()))
.filter(num => !isNaN(num))
.sort((a, b) => a - b);

if (numbers.length === 0) {
setMedian(null);
return;
}

const mid = Math.floor(numbers.length / 2);
setMedian(numbers.length % 2 !== 0 ? numbers[mid] : (numbers[mid - 1] + numbers[mid]) / 2);
};

return (
<div>
<label htmlFor="numbersInput">Enter numbers (comma-separated):</label>
<input
id="numbersInput"
type="text"
value={inputValue}
onChange={handleChange}
aria-describedby="medianDescription"
/>
<button onClick={findMedian}>Find Median</button>
<p id="medianDescription">The median of the entered numbers is: {median?.toString() ?? 'N/A'}</p>
</div>
);
};

export default MedianFinder;

chat link

This version already demonstrates fewer re-renders, and it intuitively includes a separate button for action without a direct request.

Project planning

When tackling substantial projects, start by asking ChatGPT to outline a plan. This can cover development stages, optimisation strategies, and deployment procedures.

So in case if you know react and nodejs, you can ask chat to make a plan for you, find all the information that you want and structure it:

as a software architect, make a plan for team with react and nodejs skills, how to implement web application with the best practises and optimisations and how to deploy it so end user would be able to reach it, remember that it expected about 100–200 unique users on the site, site is a web shop that advice to buy a product, allows it to configure with a lot of features and buy online, also user should be able to ask a question to support bot that should answer questions

result is available by link

The generated plan typically includes:

  • Planning
  • Development
  • Optimization
  • Deployment
  • Maintenance
  • Documentation

This structured approach acts as a checklist to guide you through the project.

Generating Code for Unfamiliar Tasks

If you’re unsure about how to approach a task, ChatGPT can provide a starting point. It can generate code and instructions based on your queries, filling in gaps in your knowledge.

As a business analyst and software architect, ask me questions regarding my system and generate code with instructions based on answers, that will implement this system.

Remember, ChatGPT is not perfect; the code might need adjustments, but it offers a solid foundation.

Example link

Unit test

You have some code, for example

import React, { useState } from 'react';

interface LoginFormProps {
onSubmit: (name: string, email: string, password: string) => void;
}

const LoginForm: React.FC<LoginFormProps> = ({ onSubmit }) => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isNameValid, setNameValid] = useState(true);
const [isEmailValid, setEmailValid] = useState(true);
const [isPasswordValid, setPasswordValid] = useState(true);

const validateEmail = (email: string): boolean => {
const re = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return re.test(email);
};

const validatePassword = (password: string): boolean => {
const re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;
return re.test(password);
};

const validateName = (name: string): boolean => {
const re = /^[a-zA-Z\s]+$/;
return re.test(name);
};

const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const name = event.target.value;
setName(name);
setNameValid(validateName(name));
};

const handleEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const email = event.target.value;
setEmail(email);
setEmailValid(validateEmail(email));
};

const handlePasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const password = event.target.value;
setPassword(password);
setPasswordValid(validatePassword(password));
};

const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
if (validateName(name) && validateEmail(email) && validatePassword(password)) {
onSubmit(name, email, password);
}
};

return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
type="text"
value={name}
onChange={handleNameChange}
required
/>
{!isNameValid && <div style={{ color: 'red' }}>Name must contain only characters</div>}
</div>
<div>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={handleEmailChange}
required
/>
{!isEmailValid && <div style={{ color: 'red' }}>Invalid email address</div>}
</div>
<div>
<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
value={password}
onChange={handlePasswordChange}
required
/>
{!isPasswordValid && <div style={{ color: 'red' }}>Password must be at least 8 characters long, include numbers, uppercase and lowercase letters, and a special character</div>}
</div>
<button type="submit">Login</button>
</form>
);
};

export default LoginForm;

Example 1

As react developer, write unit tests for following code

import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import LoginForm from './LoginForm';

describe('LoginForm Component', () => {
const mockOnSubmit = jest.fn();

beforeEach(() => {
render(<LoginForm onSubmit={mockOnSubmit} />);
});

it('renders correctly', () => {
expect(screen.getByLabelText(/name/i)).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument();
});

it('validates name field correctly', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'John123' } });
expect(screen.getByText(/name must contain only characters/i)).toBeInTheDocument();
});

it('validates email field correctly', () => {
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'invalidemail' } });
expect(screen.getByText(/invalid email address/i)).toBeInTheDocument();
});

it('validates password field correctly', () => {
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: 'short' } });
expect(screen.getByText(/password must be at least 8 characters long/i)).toBeInTheDocument();
});

it('calls onSubmit with correct values when form is submitted', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'John Doe' } });
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'john@example.com' } });
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: 'Password1!' } });
fireEvent.click(screen.getByRole('button', { name: /login/i }));

expect(mockOnSubmit).toHaveBeenCalledWith('John Doe', 'john@example.com', 'Password1!');
});

it('does not call onSubmit when form is invalid', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: '' } });
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: '' } });
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: '' } });
fireEvent.click(screen.getByRole('button', { name: /login/i }));

expect(mockOnSubmit).not.toHaveBeenCalled();
});
});

link

Actually it looks good, but can be better!

Example 2

1

use best practises of writing unit test, cover typescript react component with unit test, cover all the branches, function and if statements component should be covered for 100%, DO NOT MISS ANY CODE

2

write all the tests, don’t skip any part of it, use additional describe to union test cases

Note: sometime you need to repeat, to get the expected result

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import LoginForm from './LoginForm'; // Adjust the import path as needed

describe('LoginForm Component', () => {
const mockSubmit = jest.fn();

beforeEach(() => {
render(<LoginForm onSubmit={mockSubmit} />);
});

describe('Component Rendering', () => {
test('renders input fields and submit button', () => {
expect(screen.getByLabelText(/name/i)).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument();
});
});

describe('Input Field Changes', () => {
test('updates name input field on change', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'John Doe' } });
expect(screen.getByLabelText(/name/i)).toHaveValue('John Doe');
});

test('updates email input field on change', () => {
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'john@example.com' } });
expect(screen.getByLabelText(/email/i)).toHaveValue('john@example.com');
});

test('updates password input field on change', () => {
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: 'Password123!' } });
expect(screen.getByLabelText(/password/i)).toHaveValue('Password123!');
});
});

describe('Validation Logic', () => {
test('displays error message for invalid name', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: '12345' } });
fireEvent.blur(screen.getByLabelText(/name/i));
expect(screen.getByText(/name must contain only characters/i)).toBeInTheDocument();
});

test('displays error message for invalid email', () => {
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'invalid_email' } });
fireEvent.blur(screen.getByLabelText(/email/i));
expect(screen.getByText(/invalid email address/i)).toBeInTheDocument();
});

test('displays error message for invalid password', () => {
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: 'pass' } });
fireEvent.blur(screen.getByLabelText(/password/i));
expect(screen.getByText(/password must be at least 8 characters long/i)).toBeInTheDocument();
});
});

describe('Form Submission', () => {
test('does not call onSubmit for invalid form data', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: '' } });
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: '' } });
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: '' } });
fireEvent.click(screen.getByRole('button', { name: /login/i }));

expect(mockSubmit).not.toHaveBeenCalled();
});

test('calls onSubmit with correct data for valid form data', () => {
fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'John Doe' } });
fireEvent.change(screen.getByLabelText(/email/i), { target: { value: 'john@example.com' } });
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: 'Password123!' } });
fireEvent.click(screen.getByRole('button', { name: /login/i }));

expect(mockSubmit).toHaveBeenCalledWith('John Doe', 'john@example.com', 'Password123!');
});
});
});

Much better!

link

In the end

Always remember that while ChatGPT is a powerful tool, it’s not infallible. Its suggestions and code outputs are starting points that can streamline your development process but may require refinement.

Thank you for reading, and I hope these insights enhance your JavaScript development journey with ChatGPT.

--

--

Artsiom Marozau

I'm Software Engineer Team Lead, 10 years in web development. My scope of interest are web development, front-end architecture, people management.