Strings

Code Runner Challenge

Create

View IPYNB Source
%%js

// CODE_RUNNER: Create

// Task 1: Create your variables
let part1 = "h";
let part2 = "i";
let part3 = "!";

let secretbase = "mysecret";
let codeword = "hello";
let symbol = "!";

// Task 2: Find the number of characters in the first string.
let baseLength = secretbase.length;

// Task 3: Standardize the second string to all uppercase letters.
let fullCode = codeword.toUpperCase();

// Task 4: Combine everything to reveal the full secret.
let fullSecret = secretbase + fullCode + symbol;

// Task 5: Print the results.
console.log("The number of characters in the secret base is:");
console.log(baseLength);
console.log("The secret code is: ");
console.log(fullCode);
console.log("The full secret is: ");
console.log(fullSecret);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
%%js

// Task 1: Define your variables and strings
let ingredient = "chips";
let price = "$100";
let store = "Chips and dips";

let snackMessage =
"Attention chip lovers!\n" +
"For a limited time only, get freshly fried " + ingredient + " " +
"at " + store + " for just " + price + ".\n" +
"Don't miss your chance to taste happiness today!";

console.log("The full message is " + snackMessage.length + " characters long.");
console.log(snackMessage);
%%js

const UPGRADE_NAME = "Lucky Seven";
console.log(UPGRADE_NAME);

let cost = 7777;
console.log(cost);

let EMOJI = "🍀";
let BUTTON_CLASS = "bg-green-500 hover:bg-green-600 text-white";

const DISPLAY_NAME = UPGRADE_NAME.toUpperCase();
console.log(DISPLAY_NAME);

const NAME_LENGTH = UPGRADE_NAME.length;
console.log("Name Character Count: " + NAME_LENGTH);

let message = "Insufficient Cookies";

console.log(EMOJI + " " + UPGRADE_NAME + " (" + cost + " Cookies)");

let shopButtonText = EMOJI + " " + UPGRADE_NAME + " (" + cost + " Cookies)";
console.log(shopButtonText);

const errorDisplay = "Error: " + EMOJI + " " + UPGRADE_NAME + " purchase failed: \"" + message + "\"";
console.log(errorDisplay);

let HINT_TEXT = "The \"Lucky Seven\" upgrade multiplies your clicks by 7.";
console.log(HINT_TEXT);

Classes and Constructors

%%js

class TennisPlayer {
    constructor(name, rank, rankPoints, age) {
        this.name = name;
        this.rank = rank;
        this.rankPoints = rankPoints;
        this.age = age;
    }
    profile() {
        console.log("Hi my name is " + this.name + ", my rank is " + this.rank + ", I have " + this.rankPoints + " ranking points" + ", and I am " + this.age + " years old.");
    }
}

let player1 = new TennisPlayer("Novak Djokovic", 1, 16000, 38);
player1.profile();
%%js

class Library {
    constructor(name) {
        this.name = name;
        console.log(`Welcome to the`, this.name, `Library!`);
    }

    static Book = class {
        constructor() {
            this.books = [];
        }
        addBook(title) {
            this.books.push(title);
            console.log(`Added "${title}" to the library.`);
        }
        removeBook(title) {
            const index = this.books.indexOf(title);
            if (index > -1) {
                this.books.splice(index, 1);
                console.log(`Removed "${title}" from the library.`);
            } else {
                console.log(`"${title}" not found in the library.`);
            }
        }
    }

    static Computers = class {
        constructor(computersOn) {
            this.computersOn = computersOn;
        }
        showComputersOn() {
            console.log(`There are ${this.computersOn} computers currently on.`);
        }
    }
}

const myLibrary = new Library("Downtown");
const bookManager = new Library.Book();
const techRoom = new Library.Computers(8);

bookManager.addBook("The Hobbit");
bookManager.addBook("1984");
bookManager.removeBook("The Hobbit");
techRoom.showComputersOn();
%%js

class CookieClicker {
  constructor(cookies, cookiesPerClick, cookieType) {
    this.cookies = cookies;
    this.cookiesPerClick = cookiesPerClick;
    this.cookieType = cookieType;
  }
  click() {
    this.cookies += this.cookiesPerClick;
    console.log("You clicked a " + this.cookieType + " cookie!");
    console.log("You have " + this.cookies + " cookies.");
  }
  applyUpgrade(upgrade) {
    this.cookiesPerClick *= upgrade.multiplier;
    console.log("Upgrade applied! Multiplier: " + upgrade.multiplier);
    this.showStatus();
  }
  showStatus() {
    console.log("Each click gives " + this.cookiesPerClick + " cookies. Total: " + this.cookies);
  }
}

class Upgrade {
  constructor(multiplier) {
    this.multiplier = multiplier;
  }
}

const game = new CookieClicker(0, 1, "Chocolate chip");
game.click();
game.click();
const upgrade = new Upgrade(2);
game.applyUpgrade(upgrade);
game.click();
game.showStatus();

Iterations

%%js

function countStars(limit) {
  let count = 1;
  while (count <= limit) {
    console.log(`Star #${count} shining bright!`);
    count += 1;
  }
  console.log("All the stars have been counted.");
}

countStars(5);
%%js

function playlistShuffle(playlist) {
  for (const song of playlist) {
    console.log(`Now playing: "${song}"`);
  }
  console.log("Playlist finished!");
}

const mySongs = ["Song A", "Song B", "Song C"];
playlistShuffle(mySongs);

Data Abstraction

%%js

let username = "Hi";
let password = "hi_very_awesome_password";

function Account() {
    console.log(username, password);
}
function ChangeUsername(newUserName) {
    username = newUserName;
}
function ChangePassword(newPassword) {
    password = newPassword;
}
function Login(_username, _password) {
    if (_username === username && _password === password) {
        console.log("Login Success!");
        return true;
    } else {
        console.log("Login Failure");
        return false;
    }
}

ChangeUsername("Krish");
ChangePassword("password");
Account();
Login("Krish", "password");
Login("Krish", "P@ssword");
%%js

class House {
    constructor(cost, age, size) {
        this.cost = cost;
        this.age = age;
        this.size = size;
    }
}

let anishsHouse = new House(700000, 1, 7000);
console.log(anishsHouse);
%%js

class Player {
    constructor() {
        this.positionX = 0;
        this.velocityX = 0;
    }
    moveLeft() { this.velocityX = -100; }
    moveRight() { this.velocityX = 100; }
    updatePosition() {
        this.positionX += this.velocityX;
        console.log("Position updated to:", this.positionX);
    }
}

let player = new Player();
player.moveLeft();
player.updatePosition();
player.moveRight();
player.updatePosition();

Classes and Variables

%%js

let name = "Sam";
let age = 10;

console.log("Hi, my name is", name);
console.log("I am", age, "years old.");

let nextYearAge = age + 1;
console.log("Next year I will be " + nextYearAge + " years old");
%%js

class Animal {
  constructor(name, sound, kind) {
    this.name = name;
    this.sound = sound;
    this.kind = kind;
  }
  speak() {
    console.log(`${this.name} the ${this.kind} says ${this.sound}!`);
  }
  describe() {
    console.log(`${this.name} is a ${this.kind} and is very friendly!`);
  }
}

let zoo = [];
zoo.push(new Animal("Buddy", "Woof", "Dog"));
zoo.push(new Animal("Mittens", "Meow", "Cat"));
zoo.push(new Animal("Polly", "Squawk", "Parrot"));

zoo.forEach(animal => {
  animal.speak();
  animal.describe();
});
%%js

const choices = ["rock", "paper", "scissors"];
const computerChoice = choices[Math.floor(Math.random() * choices.length)];
const userChoice = "rock"; // change this to test different outcomes
console.log("You chose:", userChoice);
console.log("Computer chose:", computerChoice);

if (userChoice === computerChoice) {
  console.log("It's a tie!");
} else if (
  (userChoice === "rock" && computerChoice === "scissors") ||
  (userChoice === "scissors" && computerChoice === "paper") ||
  (userChoice === "paper" && computerChoice === "rock")
) {
  console.log("You win!");
} else {
  console.log("You lose!");
}

Classes and Methods

%%js

class Dice {
  constructor(sides) {
    this.sides = sides;
  }
  roll() {
    return Math.floor(Math.random() * this.sides) + 1;
  }
}

let myDice = new Dice(6);
console.log(myDice.roll());
console.log(myDice.roll());
console.log(myDice.roll());
%%js

class Pet {
  constructor(name) {
    this.name = name;
    this.hunger = 5;
    this.energy = 5;
    this.happiness = 5;
  }
  feed() {
    this.hunger -= 5;
    this.energy += 10;
    this.happiness += 10;
    console.log(this.name + "'s hunger went down by 5!");
    console.log(this.name + "'s energy went up by 10!");
    console.log(this.name + "'s happiness went up by 10!");
  }
  play() {
    this.hunger += 5;
    this.energy -= 10;
    this.happiness += 20;
    console.log(this.name + "'s hunger went up by 5!");
    console.log(this.name + "'s energy went down by 10!");
    console.log(this.name + "'s happiness went up by 20!");
  }
}

const myPet = new Pet("Pranay");
console.log("hunger: " + myPet.hunger + ", energy: " + myPet.energy + ", happiness: " + myPet.happiness);
myPet.feed();
myPet.play();
%%js

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    console.log(`Hello, my name is ${this.name}!`);
  }
}

class Book {
  constructor(title, author, pages) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.pagesRead = 0;
  }
  read(pages) {
    this.pagesRead += pages;
    if (this.pagesRead > this.pages) this.pagesRead = this.pages;
    console.log(`You have read ${this.pagesRead} out of ${this.pages} pages.`);
  }
  isLongBook() {
    return this.pages > 300;
  }
}

class Car {
  constructor(make, model, fuel) {
    this.make = make;
    this.model = model;
    this.fuel = fuel;
  }
  drive(distance) {
    const fuelNeeded = distance * 0.1;
    if (this.fuel >= fuelNeeded) {
      this.fuel -= fuelNeeded;
      console.log(`Drove ${distance} km. Fuel left: ${this.fuel.toFixed(2)} liters.`);
    } else {
      console.log("Not enough fuel.");
    }
  }
  refuel(amount) {
    this.fuel += amount;
    console.log(`Refueled. Total fuel: ${this.fuel.toFixed(2)} liters.`);
  }
  static info() {
    console.log("Cars are vehicles.");
  }
}

class ElectricCar extends Car {
  constructor(make, model, fuel, battery) {
    super(make, model, fuel);
    this.battery = battery;
  }
  charge(amount) {
    this.battery += amount;
    if (this.battery > 100) this.battery = 100;
    console.log(`Battery charged to ${this.battery}%.`);
  }
}

const person = new Person("Alice", 30);
const book = new Book("JavaScript Basics", "Anish Gupta", 350);
const car = new Car("Toyota", "Corolla", 10);
const electricCar = new ElectricCar("Tesla", "Model 3", 0, 50);

person.greet();
book.read(120);
console.log(`Is the book long? ${book.isLongBook()}`);
car.drive(50);
car.refuel(5);
electricCar.charge(30);
Car.info();

Array

%%js

let favoriteFoods = ["Ice cream", "Cookies", "Chicken", "Cake", "Apples"];
console.log("Favorite Foods: " + favoriteFoods[0]);
favoriteFoods[2] = "pizza";
favoriteFoods.push("sandwich");
console.log("Total Number of Foods: " + favoriteFoods.length);
console.log("My Favorite Foods are now: " + favoriteFoods);
%%js

let weekTemps = [66, 67, 62, 77, 74, 78, 76];
console.log("Monday Temperature: " + weekTemps[0] + " Friday Temperature: " + weekTemps[4]);

let total = 0;
for (let i = 0; i < weekTemps.length; i++) {
  total += weekTemps[i];
}
let average = total / weekTemps.length;
console.log("Average temperature:", average);

let maxTemp = Math.max(...weekTemps);
console.log("The Highest Temperature is: " + maxTemp);

let hotDay = false;
for (let i = 0; i < weekTemps.length; i++) {
  if (weekTemps[i] > 80) hotDay = true;
}
if (hotDay) {
  console.log("At least one day was above 80°F.");
} else {
  console.log("No days were above 80°F.");
}