Share
Explore

TypeScript LINKED LISTS


TypeScript object-oriented program that teaches linked lists in a relatable context and demonstrates how to use objects and arrays to build and manipulate linked lists. Let's consider a scenario where we need to manage a playlist of songs.
In this TypeScript program:
We create two classes, Song and Playlist. Song represents individual songs, and Playlist represents a collection of songs.
Each Song object contains a title, artist, and a reference to the next song in the playlist (or null for the last song).
The Playlist class provides methods to add songs, play the playlist, and shuffle the playlist.
We demonstrate how to add songs to the playlist, play the songs in order, and shuffle the playlist for a different listening experience.
This example makes the concept of linked lists more engaging and relatable by using it in the context of managing a playlist of songs.
It highlights how objects and arrays can be used to create and manipulate linked lists.

class Song {
title: string;
artist: string;
next: Song | null;

constructor(title: string, artist: string) {
this.title = title;
this.artist = artist;
this.next = null;
}

play() {
console.log(`Now playing: "${this.title}" by ${this.artist}`);
}
}

class Playlist {
head: Song | null;

constructor() {
this.head = null;
}

addSong(title: string, artist: string) {
const newSong = new Song(title, artist);

if (!this.head) {
this.head = newSong;
} else {
let currentSong = this.head;
while (currentSong.next) {
currentSong = currentSong.next;
}
currentSong.next = newSong;
}
}

playPlaylist() {
let currentSong = this.head;
if (!currentSong) {
console.log("Playlist is empty.");
} else {
while (currentSong) {
currentSong.play();
currentSong = currentSong.next;
}
}
}

shuffle() {
const songs = [];
let currentSong = this.head;
while (currentSong) {
songs.push(currentSong);
currentSong = currentSong.next;
}

for (let i = songs.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[songs[i], songs[j]] = [songs[j], songs[i]];
}

this.head = songs[0];
currentSong = this.head;
for (let i = 1; i < songs.length; i++) {
currentSong.next = songs[i];
currentSong = currentSong.next;
}
currentSong.next = null;
}
}


// Create a Playlist
const myPlaylist = new Playlist();

// Adding songs to the playlist
myPlaylist.addSong("Song 1", "Artist 1");
myPlaylist.addSong("Song 2", "Artist 2");
myPlaylist.addSong("Song 3", "Artist 3");

console.log("Playlist:");
myPlaylist.playPlaylist();

// Shuffle the playlist
myPlaylist.shuffle();

console.log("\nShuffled Playlist:");
myPlaylist.playPlaylist();



Create a full-fledged front-end web application with a back-end server using AJAX, TypeScript, HTML, and CSS


Here is a simplified example that demonstrates the architecture and basic interaction between the client and server.
server.ts (Node.js TypeScript server):
import express from 'express'; import bodyParser from 'body-parser';
const app = express(); app.use(bodyParser.json());
class Song { constructor(public title: string, public artist: string) {} }
const playlist: Song[] = [];
app.post('/api/addSong', (req, res) => { const { title, artist } = req.body; const newSong = new Song(title, artist); playlist.push(newSong); res.json({ message: 'Song added to the playlist.' }); });
app.get('/api/getPlaylist', (req, res) => { res.json(playlist); });
const port = 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); });
megaphone

index.html with CSS


In this simplified example:
We create a Node.js server using Express to handle API endpoints for adding songs and fetching the playlist.
The HTML page provides a form to input song details and a button to add songs to the playlist.
We use asynchronous JavaScript (async/await) to interact with the server and update the playlist dynamically.
The CSS is styled with a warm color palette, and it's themed around the idea of Peanut's ONLINE MUSIC Shop.
Please note that for a production-ready application, you'd need to implement proper error handling, security, and possibly a database for storing the playlist. This example is meant to provide a basic understanding of the architecture and interaction between the client and server.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Peanut's ONLINE MUSIC Shop</title> <style> body { font-family: Arial, sans-serif; background-color: #fff5e1; }
.container { text-align: center; margin: 30px; }
h1 { color: #ff6b6b; }
input[type="text"] { padding: 10px; }
button { padding: 10px; background-color: #ffa726; border: none; color: white; }
ul { list-style: none; padding: 0; }
li { margin: 10px; } </style> </head> <body> <div class="container"> <h1>Peanut's ONLINE MUSIC Shop</h1> <input type="text" id="title" placeholder="Song Title"> <input type="text" id="artist" placeholder="Artist"> <button onclick="addSong()">Add to Playlist</button> <ul id="playlist"></ul> </div>
<script> async function addSong() { const title = document.getElementById('title').value; const artist = document.getElementById('artist').value; if (title && artist) { const response = await fetch('/api/addSong', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title, artist }) });
if (response.ok) { document.getElementById('title').value = ''; document.getElementById('artist').value = ''; fetchPlaylist(); } } }
async function fetchPlaylist() { const response = await fetch('/api/getPlaylist'); if (response.ok) { const playlist = await response.json(); const playlistElement = document.getElementById('playlist'); playlistElement.innerHTML = ''; playlist.forEach(song => { const li = document.createElement('li'); li.textContent = `${song.title} by ${song.artist}`; playlistElement.appendChild(li); }); } }
// Initial playlist fetch fetchPlaylist(); </script> </body> </html>


Updated HTML
This HTML code includes the "Display Playlist" button, and it provides a simple web page for Peanut's ONLINE MUSIC Shop, where you can add songs to the playlist and display the current playlist dynamically.
megaphone
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Peanut's ONLINE MUSIC Shop</title> <style> body { font-family: Arial, sans-serif; background-color: #fff5e1; }
.container { text-align: center; margin: 30px; }
h1 { color: #ff6b6b; }
input[type="text"] { padding: 10px; }
button { padding: 10px; background-color: #ffa726; border: none; color: white; }
ul { list-style: none; padding: 0; }
li { margin: 10px; } </style> </head> <body> <div class="container"> <h1>Peanut's ONLINE MUSIC Shop</h1> <input type="text" id="title" placeholder="Song Title"> <input type="text" id="artist" placeholder="Artist"> <button onclick="addSong()">Add to Playlist</button> <button onclick="fetchPlaylist()">Display Playlist</button> <ul id="playlist"></ul> </div>
<script> async function addSong() { const title = document.getElementById('title').value; const artist = document.getElementById('artist').value; if (title && artist) { const response = await fetch('/api/addSong', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title, artist }) });
if (response.ok) { document.getElementById('title').value = ''; document.getElementById('artist').value = ''; } } }
async function fetchPlaylist() { const response = await fetch('/api/getPlaylist'); if (response.ok) { const playlist = await response.json(); const playlistElement = document.getElementById('playlist'); playlistElement.innerHTML = ''; // Clear the list before re-rendering playlist.forEach(song => { const li = document.createElement('li'); li.textContent = `${song.title} by ${song.artist}`; playlistElement.appendChild(li); }); } }
// Initial playlist fetch fetchPlaylist(); </script> </body> </html>
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.