Where can I find the code for printing a diamond shape using JavaScript?

I'm looking to design a tool where users can input odd numbers and generate diamond-shaped patterns using asterisks.

For example:

Enter an odd number: 5



   *
  ***
 *****
  ***
   *

Answer №1

If you have an input of 5, here's a simple way to learn how to count:

(spaces)(stars)
   2       1
   1       3
   0       5
   1       3
   2       1

let input = 7; // Number( prompt("Enter any odd integer") );
let space = " ";

/*****/
let breakPoint = Math.floor(input / 2);

let str = "", iter = 0, i = 0;
while( iter < input ) {
  str += (
    space.repeat( (breakPoint - i) ) +
    "*".repeat( 2 * i + 1 ) +
    "<br>"
  );
  
  (iter < breakPoint) ? (i++) : (i--);
  iter++;
}

document.body.innerHTML = str;
body { font-family: 'Lucida Console'; } /* Monospaced font required */

Instead of using two separate loops, you might find that one loop is actually simpler:

let input = 7;
let space = " ";

/***/

let breakPoint = Math.ceil(input / 2);

let str = "";

for( let i = 0; i < breakPoint - 1; i++ ) {
  str += (
    space.repeat( (breakPoint - i) ) +
    "*".repeat( 2 * i + 1 ) +
    "\n"
  );
}

for( let i = breakPoint - 1; i >= 0; i-- ) {
  str += (
    space.repeat( (breakPoint - i) ) +
    "*".repeat( 2 * i + 1 ) +
    "\n"
  );
}

console.log( str );

Another approach could be to Keep It Simple Stupid (KISS):

let input = 7;
let space = " ";

***/

let breakPoint = Math.floor(input / 2); // 3

let str = "";

let spaces = breakPoint; // (3)
let stars = 1;

for( let i = 0; i < breakPoint; i++ ) {
  str += (
    space.repeat(spaces) +
    "*".repeat(stars) +
    "\n"
  );

  spaces -= 1;
  stars += 2;
}

for( let i = breakPoint; i >= 0; i-- ) {
  str += (
    space.repeat(spaces) +
    "*".repeat(stars) +
    "\n"
  );

  spaces += 1;
  stars -= 2;
}

console.log( str );

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

Interactive Gantt chart tool designed for ReactJs with editable features

Can anyone recommend a dynamic Gantt chart component that is compatible with ReactJS? I specifically need it to display a resource Gantt chart where users can easily manipulate tasks along the time axis and switch between different resources. It would be ...

Creating reusable JavaScript functions in RunnerTest.java within the Karate framework

I have been working with the Karate framework and have successfully created multiple feature files. Within each feature file, there is a common JavaScript function that is responsible for inserting specified data into an InfluxDB. This is how one of my f ...

Retrieving the UTC offset value from a timestamp string in Node.js/JavaScript

Having a local timestamp presented as a string in the format shown below: '2020-05-19T15:45:07.2306062+05:30' I am trying to figure out how to extract the UTC offset value from this specific date string using nodejs/javascript. Any assistance w ...

Comparison of MVC5 and Angular JS: Which is the better framework

For the past year, I've been immersed in ASP.NET MVC and have found joy in building SPA's using tools like: Partial views(via html.action() and renderPartial()) Ajax helpers (Ajax.Actionlink() and Ajax.beginform()) Now, I'm curious ...

Address a security flaw in the package-lock.json file

After running npm audit on my project, I received the following results: nth-check <2.0.1 Severity: high Inefficient Regular Expression Complexity in nth-check - https://github.com/advisories/GHSA-rp65-9cf3-cjxr fix available via `npm audit fix --force ...

The vue-pdf is having trouble loading all pages due to an "undefined property" issue

I am currently utilizing the following technologies: Vue.js, vue-route, Vuetify, Firebase (with a database) and vue-pdf The issue I am facing involves attempting to load all pdf pages using "vue-pdf" plugin. However, when trying to read the pdf, I encoun ...

State is not currently utilizing the variable

const DonorsTables = () =>{ const [search, setSearch] = useState(""); const [countries, setCountries] = useState([]); const [filteredcountries, setFilteredCountries] = useState([]); const getCountries = async () => { try { ...

How to ensure product images keep their size and aspect ratio in Weebly

Currently, I am running into issues while using Weebly to create an eCommerce website. The problem lies with the product element images - they seem to be appearing twice the size of the original upload. Unfortunately, I do not have access to any other imag ...

What are alternative ways to retrieve data from a different server using AJAX without relying on JSONP?

I am currently dealing with a project where the back-end code is located on ServerA, while my front-end code is on ServerB, belonging to different domains. Due to the same origin policy, I am facing difficulties in successfully making AJAX requests (both P ...

Reveal or conceal elements with a touch of animation

I am in the process of building my own website and I've been working on implementing a button that can toggle the visibility of a specific div element. While the functionality is there, I really want to incorporate an animation to enhance it. I attem ...

JavaScript list items experience unreliability once stored in the database

I am in the process of setting up an ajax endpoint on my server to create a new transaction object and add it to a block, which is then added to a local blockchain. The problem arises when I invoke my database function add_block, responsible for adding th ...

Modifying Regular Expression to eliminate trailing decimal points and zeroes when there is no fractional value present

Currently, I am in the process of learning Regex and experimenting with it. One thing I'm working on is creating a function that parses a float number while limiting the number of decimal places. My goal is to only allow a maximum of two decimal point ...

I'm having trouble getting Tailwind CSS colors to work with my Next.js components. Any tips on how to apply background colors

https://i.stack.imgur.com/8RGS3.png https://i.stack.imgur.com/FRTOn.png Hey there! I'm currently experimenting with using Tailwind background colors in my Next.js project. However, I'm facing an issue where the background color is not being appl ...

Leveraging jQuery selectors to manipulate data received from an Ajax response

I am encountering an issue with an Ajax call and response. Previously, I had a block of regular javascript code that successfully transformed my select element into a select2 widget. However, when I attempt to convert the select element into a select2 usi ...

React-dom is throwing a hook call error. How do I fix this?

I am looking to implement a global modal component using redux/toolkit for global management. Upon clicking the drop-down menu, I specify the message to display in the modal. I aim to close the modal by clicking either the Ok or Cancel button or the backgr ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

How can I configure the domain in a Localstorage offline JS app to access local storage from multiple HTML files?

For a small JS/HTML app I am developing, I need to store preferences in LocalStorage and access them from two different HTML files. While it works fine when staying on the same HTML file, accessing the stored data from another HTML page poses a challenge. ...

Invoking a directive function when the template is loaded

<div ng-app="myApp"> <div greeting ng-click="greeting()">directive</div> </div> Is there a way to call a method when the template loads in AngularJS? I attempted to use ng-init, but it did not work as expected. angular.module( ...

Tips for swapping out a specific string in an HTML webpage with a different string using JavaScript

For my HTML website, I am trying to replace one string with another using JavaScript. Specifically, within the nodeList "AuthorList," there is a string called "Test String" that needs to be changed to "new test." I have attempted various modifications of ...

Babeljs encountered an error: TypeError - The super expression should be a function or null, not undefined

Currently, my project involves implementing multiple-files inheritance in ES6 using Node.js and Babel. Babel is used to convert the ES6 code to ES5 since Node does not fully support ES6 yet. Import/export statements are used to connect the different files ...