What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer

Here is how I've modified the last line:

1 bottle of beer on the wall, 1 bottle of beer.
Take it down and pass it around,
no more bottle of beer on the wall.

How can I include an additional line starting with a capital letter?

No more bottles of beer on the wall, no more bottles of beer.
Head to the store and buy some more, 99 bottles of beer on the wall.

var beer = 99;
while (beer >= 0) {
  var words = "bottles";
  if (beer === 1) {
    words = "bottle";
  }
  console.log(beer + " " + words + " of beer on the wall, " + beer + " " + words + " of beer. Take one down and pass it around, ");
  beer--;
  if (beer === 1) {
    words = "bottle";
  }
  if (beer === 0) {
    beer = "no more";
  }
  console.log(beer + " " + words + " of beer on the wall.");
}

Answer №1

You may also insert the console.log within the if loop

var beer = 99;
while (beer >= 0) {
  var words = beer === 1 ? "bottle" : "bottles";
  console.log(beer + " " + words + " of beer on the wall, " + beer + " " + words + " of beer. Take one down and pass it around, ");

  beer--;

  words = beer === 1 ? "bottle" : "bottles";

  if (beer === 0) {
    beer = "no more";
    console.log(beer + " " + words + " of beer on the wall.");
    console.log("No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.");
  } else {
    console.log(beer + " " + words + " of beer on the wall.");
  }
}

Answer №2

Take a look at the other responses for ways to enhance your current code

Below is my attempt at making it as DRY as possible.

const plur = (word, count) => count === 0 ? `no more ${word}s` : `${count} ${word}${count === 1 ? "" : "s"}`;
const capitalize = str => `${str.slice(0,1).toUpperCase()}${str.slice(1)}`;
const onTheWall = 'of beer on the wall';
for (let beer = 99; beer >= 0; beer--) {
    let beerText = plur("bottle",beer);
    let nextBeerText = plur("bottle",beer-1);
    const lines = [
        `${beerText} ${onTheWall}, ${beerText} of beer.`,
        beer > 0 ? `Take one down and pass it around,` : `Go to the store and buy some more,`,
        `${beer > 0 ? nextBeerText : plur("bottle", 99)} ${onTheWall}.`
    ];
    if(beer === 0) lines[0] =  capitalize(lines[0]);
    console.log(lines.join("\n"));
}

Here's another version for entertainment and learning purposes

const maxBeers = 99;
const plur = (word, count) => count === 0 ? `no more ${word}s` : `${count} ${word}${count === 1 ? "" : "s"}`;
const capitalize = str => `${str.slice(0, 1).toUpperCase()}${str.slice(1)}`;
const onTheWall = 'of beer on the wall';

const song = Array.from({ length: maxBeers + 1 }, (_, beer) => {
    beer = maxBeers - beer;
    let beerText = plur("bottle", beer);
    let nextBeerText = plur("bottle", beer - 1);

    let lines = [
        `${beerText} ${onTheWall}, ${beerText} of beer.`,
        beer > 0 ? `Take one down and pass it around,` : `Go to the store and buy some more,`,
        `${beer > 0 ? nextBeerText : plur("bottle", maxBeers)} ${onTheWall}.`
    ];

    if (beer === 0) lines[0] = capitalize(lines[0]);
    return lines.join("\n");
});

console.log(song.join("\n---\n"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Transferring PHP array data to JavaScript using echo

I'm currently in the process of working on a project that requires extracting data from a database and converting it into a JavaScript array. This array will be used to dynamically update a graph. Below is the PHP code I have written to retrieve the ...

Using jQuery to send data with an AJAX post request when submitting a form with

This is the code I'm working with: <html> <body> <?php include('header.php'); ?> <div class="page_rank"> <form name="search" id="searchForm" method="post"> <span class="my_up_text">ENTER THE WEBSITE TO ...

What is the best approach for rendering content to a page in ReactJS when a user clicks on a dynamic URL?

One challenge I am currently tackling is how to direct users to a specific page when they click on a dynamic URL. Specifically, within my "product_list" API data, there exists a key called "url". Upon clicking this "url", the user should be redirected to a ...

Restricting the drop zone for a jqueryui sortable element

In my HTML code, I have a list of elements inside a ul tag. The last li element is supposed to create new items. I used jqueryui's sortable() function to make the ul sortable, but excluded the last li element from being draggable. However, other items ...

When using VueJS routing with the same component, the OWL Carousel does not get triggered

Hello I am currently experiencing an issue with VueJS rendering images into a Carousel plugin (OwlCarousel) when loading the same component with different variables. When initially loading the page with images, everything functions correctly and the caro ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...

Tone.js is failing to sync sequences during playback

I'm currently working on developing a sequencer using Tone.js. Right now, I have a basic sequence that plays when the user clicks the play button. However, I've encountered an issue where if the button is pressed to pause and then played again, t ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

Guide on implementing "Displaying 1 of N Records" using the dataTables.js framework

let userTable = $("#user_table").DataTable({ 'sDom': '<"row-drop"<"col-sm-12 row"lr>><"row"t><"row-pager"<"col-sm-12 col-md-5"i><"col-sm-12&qu ...

When attempting to make a post using Prisma's ORM, users may encounter an error message indicating that the post function

Creating a basic prisma application using express and node to query a local mysql database. Encountering an error when calling await prisa.list.create(), details provided below. Here is the script.js code snippet from the HTML page: addItemForm.addEvent ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

Discover a simple method for comparing JSON responses and UI elements by utilizing two arrays in a for loop within your Cypress automation tests

I am in need of assistance where I must compare JSON response data with UI elements. If matching elements are found, the task is to print them in a log file. This requires checking all JSON responses using a for loop. Can someone provide me with Cypress Ja ...

How to dynamically insert a key into an array by locating a specific value in AngularJS

I need help adding a new key to a JSON array by searching for a specific key value. For example JSON:- [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", ...

Exploring the process of sending post data and navigating to a URL using AngularJS

I am working on an application using angularjs 1.6 and Java 8. My goal is to send POST data to another application and navigate to the URL that this external application determines. The purpose of my application is to transmit data about a citizen who wan ...

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

Updating the rotation of a grandchild in Three.js Object3D

In my current project, I am attempting to make the grandchild of a rotated Object3D element face towards the camera using the lookAt() method. I have experimented with various approaches to achieve this. However, the source code for the Object3D.lookAt() ...

When a div is modified through an ajax function, I aim to activate a JavaScript function

Is there a way to automatically execute a javascript function once the status updates to "Upload successful"? I am uncertain about how to accomplish this task. Following a multi file upload, the status will switch based on whether it was successful or en ...

During model update, AngularJS experienced a loss of CSS class in DOM re-rendering

My challenge involves managing a table that dynamically updates via WebSocket messages, causing the selection state to be lost. The rows in this table loop through model data, and upon clicking a cell, all cells in the same row toggle to have an .active cl ...

Navigating a Mesh in 3D Space using three.js, Camera Movement, and physi.js

I am attempting to manipulate an object in Three.js using Physi.js. The camera is linked to the moving mesh, and I am moving it using .setLinearVelocity(); Additionally, I rotate it using .setAngularVelocity(); However, the issue I am facing is that whil ...