JavaScript: Numerical Grade to Letter Grade - javascript

1. Create a function toLetterGrade that takes an array of percentages and returns an array of corresponding grade letters. For example:
toLetterGrade([90,80,55,85]); //returns ["A","A-","C","A"]
2. Create a function toGradePoints that takes an array of letter grades and returns a corresponding array of grades points. For example:
toGradePoints(["A","A-","C","A"]); //returns [4.0,3.7,2.0,4.0]
3. Create a function GPA that takes an array of percentages and returns the corresponding grade point average.
I'm trying to do number 1, and this is the code I have so far, but it only gives me the letter grade for the last number in the array. What am I doing wrong?
var arr
function toLetterGrade(arr) {
for (i = 0; i < arr.length; i++) {
if (arr[i] >= 85) {
textG = "A";
} else if (arr[i] >= 80) {
textG = "A-";
} else if (arr[i] >= 75) {
textG = "B+";
} else if (arr[i] >= 70) {
textG = "B";
} else if (arr[i] >= 65) {
textG = "B-";
} else if (arr[i] >= 60) {
textG = "C+";
} else if (arr[i] >= 55) {
textG = "C";
} else if (arr[i] >= 50) {
textG = "D";
} else {
textG = "F";
}
}
return textG;
}
document.write(toLetterGrade([90, 80, 70]))
Output is B.

You are overwriting your variable with every cycle of the loop, that's why you are getting only one - the last grade.
I suggest you to use an empty array variable to store results inside.
With every loop you will assign new grade to the textG variable and then push it into the result array. The textG variable gets reseted with every loop textG = '' so there's no risk to duplicate/overwrite results.
After all cycles of the for loop, the result array is returned.
function toLetterGrade(arr) {
var textG = '';
var result = [];
for (i = 0; i < arr.length; i++) {
textG = '';
if (arr[i] >= 85) {
textG = "A";
} else if (arr[i] >= 80) {
textG = "A-";
} else if (arr[i] >= 75) {
textG = "B+";
} else if (arr[i] >= 70) {
textG = "B";
} else if (arr[i] >= 65) {
textG = "B-";
} else if (arr[i] >= 60) {
textG = "C+";
} else if (arr[i] >= 55) {
textG = "C";
} else if (arr[i] >= 50) {
textG = "D";
} else {
textG = "F";
}
result.push(textG);
}
return result;
}
document.write(toLetterGrade([90, 80, 70]))

For the first part, you could use an object and iterate the keys for the wanted grade.
function getGrade(p) {
var grade = 'F';
Object.keys(grades).some(function (k) {
if (p >= grades[k]) {
grade = k;
return true;
}
});
return grade
}
var grades = { A: 85, 'A-': 80, B: 70, 'B-': 65, 'C+': 60, C: 55, D: 50, F: '' }
console.log([90, 80, 55, 85].map(getGrade));
.as-console-wrapper { max-height: 100% !important; top: 0; }

You're assigning the grade to a variable and then overwriting it with each iteration.
try textG.push('A') instead

You are overwriting your return value with each iteration.
Try creating an array, and adding the solution onto the array.
var solutionArr = [];
solutionArr.push("A");
jsfiddle

I make this simple code to check letter grade from a numerical
const letterGrade = (n) => {
let resultGrade = "";
if (n >= 90) {
resultGrade = "A";
} else if (n >= 80 || n > 89) {
resultGrade = "B";
} else if (n >= 70 || n > 79) {
resultGrade = "C";
} else if (n >= 60 || n > 69) {
resultGrade = "D";
} else if (n < 59) {
resultGrade = "E";
} else {
alert("Input your grade first");
}
return `Your grade is ${resultGrade}`;
};
console.log(letterGrade(75));

Related

Why is my isNaN not working in my if statement

new to JS. In the following code, the isNaN isn't working. If you enter a number in the prompt, the FizzBuzz rules work fine. However, if you enter a random string, I expect the isNaN condition to be met. What am I doing wrong?
let number = parseInt(prompt("Enter a number"));
for(let i = 1; i < number; i++) {
if(isNaN(number)) {
console.log("Is not a number")
} else if(i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")
} else if (i % 3 === 0) {
console.log("Fizz")
} else if (i % 5 === 0) {
console.log("Buzz")
} else {
console.log(i)
}
}
When parseInt can't parse the string to an integer if will return NaN. In your for loop you use number in the condition i < number. If NaN is compared to a number using a comparison operator such as < or > the result will always be false and the loop will not run at all, this is why nothing happens when you enter a random string.
To get the result you are expecting You could put the isNaN check outside the for loop and only run the loop if number is not equal to NaN.
let number = parseInt(prompt("Enter a number"));
if (isNaN(number)) {
console.log("Is not a number")
} else {
for(let i = 1; i < number; i++) {
if(i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")
} else if (i % 3 === 0) {
console.log("Fizz")
} else if (i % 5 === 0) {
console.log("Buzz")
} else {
console.log(i)
}
}
}
As #RobinZigmond correctly pointed out, when you enter an arbitrary string, number will be NaN.
For loop basically consists of:
for (Initialization, Condition, Increment)
Your condition: let i = 1 is run one time, then your condition: i < number is checked, in this case 1 < NaN which is clearly false, as the condition here is not met, you never enter your for loop.
One way to do what you're trying to do is:
let number;
while (!isNaN(number)) {
number = parseInt(prompt("Enter a number"));
}
for(let i = 1; i < number; i++) {
if(i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")
} else if (i % 3 === 0) {
console.log("Fizz")
} else if (i % 5 === 0) {
console.log("Buzz")
} else {
console.log(i)
}
}
let userInput = prompt("Enter a number");
if(isNaN(userInput)) {
console.log("Is not a number")
} else {
let number = parseInt(userInput);
for(let i = 1; i < number; i++) {
if(i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")
} else if (i % 3 === 0) {
console.log("Fizz")
} else if (i % 5 === 0) {
console.log("Buzz")
} else {
console.log(i)
}
}
}
This works as expected (putting the isNaN check outside of the loop.
Move your first if statement out of the loop. It never gets read, because the expression parseInt(string) < number will always return false.
let number = parseInt(prompt("Enter a number"));
if (isNaN(number)) {
console.log("Is not a number")
}
for (let i = 1; i < number; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")
} else if (i % 3 === 0) {
console.log("Fizz")
} else if (i % 5 === 0) {
console.log("Buzz")
} else {
console.log(i)
}
}

Javascript: Average Grade and Letter Grade of Students

I was looking at this Javascript code to calculate the average grade of an array of students and then based on the result decide which letter grade should be assigned. I was wondering how would you display these two results in your HTML? I've played around and tried a few things but nothing seems to work. I'm also new to Javascript so the solution is most likely very simple but I'm just not sure how to go about it.
var students = [80, 77, 88, 95, 68];
var Avgmarks = 0;
for (var i = 0; i < students.length; i++) {
Avgmarks += students[i][1];
var avg = (Avgmarks / students.length);
}
console.log("Average grade: " + (Avgmarks) / students.length);
if (avg < 60) {
console.log("Grade : F");
} else if (avg < 70) {
console.log("Grade : D");
} else if (avg < 80) {
console.log("Grade : C");
} else if (avg < 90) {
console.log("Grade : B");
} else if (avg < 100) {
console.log("Grade : A");
}
EDIT: 09/10/2019
I have revised my code to this:
let students = [80, 77, 88, 95, 68];
let avgMarks = 0;
for (let i = 0; i < students.length; i++) {
avgMarks += students[i];
}
let avg = avgMarks / students.length;
if (avg <= 60) {
document.write("Grade : F");
}
else if (avg <= 70) {
document.write("Grade : D");
}
else if (avg <= 80) {
document.write("Grade : C");
}
else if (avg <= 90) {
document.write("Grade : B");
} else {
document.write("Grade : A");
}
document.getElementById("studentAvgGrade").innerHTML = avg;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Average Student Grade and Letter Grade</title>
</head>
<body>
<div id="studentAvgGrade"></div>
</body>
</html>
My code is now working. Thank you everyone for your help.
I would however like to know if this is the best way to go about solving the task using pure Javascript or is there a better way?
You can set the element with
const element = document.querySelector(YOUR HTML ELEMENT SELECTOR);
Then inside each if statement
element.innerText = grade
First declare a new variable for grade:
let grade = ""
then inside of your if/else statement variable grade gets assigned a new value with each condition.
in your html select the element where you would want it to appear and then assign variable grade as its innerhtml.:
<h1 id='grading'></h1>
and in your js:
let grade = ""
if (avg < 60){
console.log("Grade : F");
grade = "F"
}
else if (avg < 70) {
console.log("Grade : D");
grade = "D"
}
else if (avg < 80)
{
console.log("Grade : C");
grade = "C"
} else if (avg < 90) {
console.log("Grade : B");
grade = "B"
} else if (avg < 100) {
console.log("Grade : A");
grade = "A"
}
const gradeToDisplay = document.getElementById("grading")
grading.innerHTML = grade

number to grade letter

As a recent assignment for my coding bootcamp, we've been asked to create a function that takes an array of numbers as an argument and outputs them to an array of letter grades. I am stuck!
I've tried re-working and refactoring my code, changing the placement of different parts of the program, looking through MDN...
let grades = []
function getLetterGrades(grades) {
let grade = grades.map
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
console.log(grades);
}
getLetterGrades([95, 85, 71]);
The results will only output the numbers I've entered into the function call.
You are using .map() wrong. What you are doing is comparing the map method to a number. You are not executing anything.
function getLetterGrades(grades) {
return grades.map(function(grade) {
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
});
}
var letters = getLetterGrades([95, 85, 71]);
console.log(letters)
Your main issue is this:
let grade = grades.map
You are not invoking the .map method with (), so instead grade is winding up holding a reference to the native map function. And, that function isn't a number, so none of your conditions become true, so you continue past the if statement and just log the array that you passed in.
Instead, you must invoke .map() and supply its required parameter (a function that will be called for each item in the source array). Your if statement should be the body of that function:
let grades = []
function getLetterGrades(grades) {
let letterGrades = grades.map(function(grade){
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
});
console.log(letterGrades);
}
getLetterGrades([95, 85, 71]);
Look at this solution:
let grades = []
function getLetterGrades(grades) {
// add an array (grade) that will hold the output
let grade = []
// iterate over grades with forEach()
grades.forEach(item => {
// item will be equal 95 on the first iteration
// 85 on the second, and 71 on the third - these
// values come from the passed 'grades' parameter
if (item < 60) {
grade.push("F");
} else if (item < 70) {
grade.push("D");
} else if (item < 80) {
grade.push("C");
} else if (item < 90) {
grade.push("B");
} else if (item < 100) {
grade.push("A");
}
})
// console.log(grade) - NOT grades!
console.log(grade);
}
getLetterGrades([95, 85, 71]);
The problem was not with the method you chose - the problem was you didn't finish your function. Here's another solution with map():
let grades = []
function getLetterGrades(grades) {
let grade = grades.map(item => {
if (item < 60) {
return "F";
} else if (item < 70) {
return "D";
} else if (item < 80) {
return "C";
} else if (item < 90) {
return "B";
} else if (item < 100) {
return "A";
}
})
// console.log(grade) - NOT grades!
console.log(grade);
}
getLetterGrades([95, 85, 71]);
In this case the main difference between forEach() and map() is that map() returns a NEW array (that's why you return values in the function body), and forEach() doesn't (we had to create the array - grade- manually, and push values into this "hand-made" array).
Look below to see what would happen, if we used forEach() WITHOUT a manually created array:
// THIS IS NOT A GOOD SOLUTION!
// IT GIVES YOU THE ANSWER IN THIS SMALL EXAMPLE
// (so you see that it's possible)
// BUT IN ANY LARGER CODE THIS IS THE
// 100% SURE SOURCE OF ERRORS.
let grades = []
function getLetterGrades(grades) {
grades.forEach((item, index) => {
if (item < 60) {
grades[index] = "F";
} else if (item < 70) {
grades[index] = "D";
} else if (item < 80) {
grades[index] = "C";
} else if (item < 90) {
grades[index] = "B";
} else if (item < 100) {
grades[index] = "A";
}
})
// console.log(grades) - NOT grade!
console.log(grades);
}
getLetterGrades([95, 85, 71]);
(I used the second argument of forEach() - that's index) THIS IS NOT A GOOD SOLUTION! Why? We "destroyed" our original grades array by overwriting it in getLetterGrades() - DON'T DO THIS!
As stated on map() takes a function and runs it once on each object in the array. To be clear on how you're trying to use it:
function getLetterGrades(grade) {
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
}
x = [95, 85, 71];
//=> [A, B, C]
x.map(getLetterGrades);
Functionally, this is what the other answers are doing, they just aren't naming the method.
Post edited to change link as comment pointed out better resource.

Wierd execution of if condition

Else condition is executed every time. If input is '11' answer is 'f' not 'D', I know the last condition should be else if but according to the logic of input is 11 output should be 'D'
function getGrade(score) {
let grade;
var score1 = Number(score);
// Write your code here
if (score1 > 25 && score <= 30)
grade = "A";
else if (score1 > 20 && score <= 25)
grade = "B";
else if (score1 > 15 && score <= 20)
grade = "C";
else if (score1 > 10 && score <= 15)
grade = "D";
else if (score1 > 5 && score <= 10)
grade = "E";
else (score1 > 0 && score <= 5)
grade = "F";
return grade;
}
Is it a copy-paste? Then it's a matter of typo.
else (score1 > 0 && score <= 5)
grade = "F";
if is missing here. Therefore, (score1 > 0 && score <= 5) is interpreted as the thing to do (so, evaluate an expression), and the next line is outside of any else/if branch and simply gets executed always.
You can use the parenthesis around the else if. Also for the last condition you can simple use else instead of else if
function getGrade(score) {
let grade;
var score1 = Number(score);
console.log(score1)
// Write your code here
if (score1 > 25 && score <= 30) {
grade = "A";
} else if (score1 > 20 && score <= 25) {
grade = "B";
} else if (score1 > 15 && score <= 20) {
grade = "C";
} else if (score1 > 10 && score <= 15) {
grade = "D";
} else if (score1 > 5 && score <= 10) {
grade = "E";
} else {
grade = "F";
}
return grade;
}
console.log(getGrade(11))
A better approach, is to use an early exit paradigm, starting with wrong values and then take a ladder of conditions which rely on the conditions before.
function getGrade(score) {
var score1 = Number(score);
if (isNaN(score1) || score1 > 30 || score1 < 0) return;
if (score1 > 25) return "A";
if (score1 > 20) return "B";
if (score1 > 15) return "C";
if (score1 > 10) return "D";
if (score1 > 5) return "E";
return "F";
}

FizzBuzz program (details given) in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.
Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
function isDivisible(numa, num) {
if (numa % num == 0) {
return true;
} else {
return false;
}
};
function by3(num) {
if (isDivisible(num, 3)) {
console.log("Fizz");
} else {
return false;
}
};
function by5(num) {
if (isDivisible(num, 5)) {
console.log("Buzz");
} else {
return false;
}
};
for (var a=1; a<=100; a++) {
if (by3(a)) {
by3(a);
if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log("\n");
}
} else if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log(a+"\n")
}
}
for (let i = 1; i <= 100; i++) {
let out = '';
if (i % 3 === 0) out += 'Fizz';
if (i % 5 === 0) out += 'Buzz';
console.log(out || i);
}
/*Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”*/
var str="",x,y,a;
for (a=1;a<=100;a++)
{
x = a%3 ==0;
y = a%5 ==0;
if(x)
{
str+="fizz"
}
if (y)
{
str+="buzz"
}
if (!(x||y))
{
str+=a;
}
str+="\n"
}
console.log(str);
Your functions return falsy values no matter what, but will print anyway. No need to make this overly complicated.
fiddle: http://jsfiddle.net/ben336/7c9KN/
Was fooling around with FizzBuzz and JavaScript as comparison to C#.
Here's my version, heavily influenced by more rigid languages:
function FizzBuzz(aTarget) {
for (var i = 1; i <= aTarget; i++) {
var result = "";
if (i%3 === 0) result += "Fizz";
if (i%5 === 0) result += "Buzz";
if (result.length ===0) result = i;
console.log(result);
}
}
I like the structure and ease of read.
Now, what Trevor Dixon cleverly did is relay on the false-y values of the language (false , null , undefined , '' (the empty string) , 0 and NaN (Not a Number)) to shorten the code.
Now, the if (result.length ===0) result = i; line is redundant and the code will look like:
function FizzBuzz(aTarget) {
for (var i = 1; i <= aTarget; i++) {
var result = "";
if (i%3 === 0) result += "Fizz";
if (i%5 === 0) result += "Buzz";
console.log(result || i);
}
}
Here we relay on the || operator to say : "if result is false, print the iteration value (i)". Cool trick, and I guess I need to play more with JavaScript in order to assimilate this logic.
You can see other examples (from GitHub) that will range from things like :
for (var i=1; i <= 20; i++)
{
if (i % 15 == 0)
console.log("FizzBuzz");
else if (i % 3 == 0)
console.log("Fizz");
else if (i % 5 == 0)
console.log("Buzz");
else
console.log(i);
}
No variables here, and just check for division by 15,3 & 5 (my above one only divides by 3 & 5, but has an extra variable, so I guess it's down to microbenchmarking for those who care, or style preferences).
To:
for(i=0;i<100;)console.log((++i%3?'':'Fizz')+(i%5?'':'Buzz')||i)
Which does it all in on line, relaying on the fact that 0 is a false value, so you can use that for the if-else shorthanded version (? :), in addition to the || trick we've seen before.
Here's a more readable version of the above, with some variables:
for (var i = 1; i <= 100; i++) {
var f = i % 3 == 0, b = i % 5 == 0;
console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}
All in all, you can do it in different ways, and I hope you picked up some nifty tips for use in JavaScript :)
.fizz and .buzz could be CSS classes, no? In which case:
var n = 0;
var b = document.querySelector("output");
window.setInterval(function () {
n++;
b.classList[n%3 ? "remove" : "add"]("fizz");
b.classList[n%5 ? "remove" : "add"]("buzz");
b.textContent = n;
}, 500);
output.fizz:after {
content: " fizz";
color:red;
}
output.buzz:after {
content: " buzz";
color:blue;
}
output.fizz.buzz:after {
content: " fizzbuzz";
color:magenta;
}
<output>0</output>
With ternary operator it is much simple:
for (var i = 0; i <= 100; i++) {
str = (i % 5 == 0 && i % 3 == 0) ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0) ? "Buzz" : i);
console.log(str);
}
for(i = 1; i < 101; i++) {
if(i % 3 === 0) {
if(i % 5 === 0) {
console.log("FizzBuzz");
}
else {
console.log("Fizz");
}
}
else if(i % 5 === 0) {
console.log("Buzz");
}
else {
console.log(i)
}
}
In your by3 and by5 functions, you implicitly return undefined if it is applicable and false if it's not applicable, but your if statement is testing as if it returned true or false. Return true explicitly if it is applicable so your if statement picks it up.
As an ES6 generator: http://www.es6fiddle.net/i9lhnt2v/
function* FizzBuzz() {
let index = 0;
while (true) {
let value = ''; index++;
if (index % 3 === 0) value += 'Fizz';
if (index % 5 === 0) value += 'Buzz';
yield value || index;
}
}
let fb = FizzBuzz();
for (let index = 0; index < 100; index++) {
console.log(fb.next().value);
}
Codeacademy sprang a FizzBuzz on me tonight. I had a vague memory that it was "a thing" so I did this. Not the best way, perhaps, but different from the above:
var data = {
Fizz:3,
Buzz:5
};
for (var i=1;i<=100;i++) {
var value = '';
for (var k in data) {
value += i%data[k]?'':k;
}
console.log(value?value:i);
}
It relies on data rather than code. I think that if there is an advantage to this approach, it is that you can go FizzBuzzBing 3 5 7 or further without adding additional logic, provided that you assign the object elements in the order your rules specify. For example:
var data = {
Fizz:3,
Buzz:5,
Bing:7,
Boom:11,
Zing:13
};
for (var i=1;i<=1000;i++) {
var value = '';
for (var k in data) {
value += i%data[k]?'':k;
}
console.log(value?value:i);
}
This is what I wrote:
for (var num = 1; num<101; num = num + 1) {
if (num % 5 == 0 && num % 3 == 0) {
console.log("FizzBuzz");
}
else if (num % 5 == 0) {
console.log("Buzz");
}
else if (num % 3 == 0) {
console.log("Fizz");
}
else {
console.log(num);
}
}
for (var i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) console.log("FizzBuzz");
else if (i%3 === 0) console.log("Fizz");
else if (i%5 === 0) console.log("Buzz");
else console.log(i);
}
One of the easiest way to FizzBuzz.
Multiple of 3 and 5, at the same time, means multiple of 15.
Second version:
for (var i = 1; i <= 100; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i%3 === 0) console.log("Fizz");
else if (i%5 === 0) console.log("Buzz");
else console.log(i);
}
In case someone is looking for other solutions: This one is a pure, recursive, and reusable function with optionally customizable parameter values:
const fizzBuzz = (from = 1, till = 100, ruleMap = {
3: "Fizz",
5: "Buzz",
}) => from > till || console.log(
Object.keys(ruleMap)
.filter(number => from % number === 0)
.map(number => ruleMap[number]).join("") || from
) || fizzBuzz(from + 1, till, ruleMap);
// Usage:
fizzBuzz(/*Default values*/);
The from > till is the anchor to break the recursion. Since it returns false until from is higher than till, it goes to the next statement (console.log):
Object.keys returns an array of object properties in the given ruleMap which are 3 and 5 by default in our case.
Then, it iterates through the numbers and returns only those which are divisible by the from (0 as rest).
Then, it iterates through the filtered numbers and outputs the saying according to the rule.
If, however, the filter method returned an empty array ([], no results found), it outputs just the current from value because the join method at the end finally returns just an empty string ("") which is a falsy value.
Since console.log always returns undefined, it goes to the next statement and calls itself again incrementing the from value by 1.
A Functional version of FizzBuzz
const dot = (a,b) => x => a(b(x));
const id = x => x;
function fizzbuzz(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dot(f(3, 'fizz'), f(5, 'buzz')) (id) (n);
}
for more options in the above replace dot with dots as below
const dots = (...a) => f0 => a.reduceRight((acc, f) => f(acc), f0);
function fizzbuzz(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dots(f(3, 'fizz'), f(5, 'buzz'), f(7, 'bam')) (id) (n);
}
Reference: FizzBuzz in Haskell by Embedding a Domain-Specific Language
by Maciej Piro ́g
for (i=1; i<=100; i++) {
output = "";
if (i%5==0) output = "buzz";
if (i%3==0) output = "fizz" + output;
if (output=="") output = i;
console.log(output);
}
Functional style! JSBin Demo
// create a iterable array with a length of 100
// and map every value to a random number from 1 to a 100
var series = Array.apply(null, Array(100)).map(function() {
return Math.round(Math.random() * 100) + 1;
});
// define the fizzbuzz function which takes an interger as input
// it evaluates the case expressions similar to Haskell's guards
var fizzbuzz = function (item) {
switch (true) {
case item % 15 === 0:
console.log('fizzbuzz');
break;
case item % 3 === 0:
console.log('fizz');
break;
case item % 5 === 0:
console.log('buzz');
break;
default:
console.log(item);
break;
}
};
// map the series values to the fizzbuzz function
series.map(fizzbuzz);
Another solution, avoiding excess divisions and eliminating excess spaces between "Fizz" and "Buzz":
var num = 1;
var FIZZ = 3; // why not make this easily modded?
var BUZZ = 5; // ditto
var UPTO = 100; // ditto
// and easily extended to other effervescent sounds
while (num < UPTO)
{
var flag = false;
if (num % FIZZ == 0) { document.write ("Fizz"); flag = true; }
if (num % BUZZ == 0) { document.write ("Buzz"); flag = true; }
if (flag == false) { document.write (num); }
document.write ("<br>");
num += 1;
}
If you're using using jscript/jsc/.net, use Console.Write(). If you're using using Node.js, use process.stdout.write(). Unfortunately, console.log() appends newlines and ignores backspaces, so it's unusable for this purpose. You could also probably append to a string and print it. (I'm a complete n00b, but I think (ok, hope) I've been reasonably thorough.)
"Whaddya think, sirs?"
check this out!
function fizzBuzz(){
for(var i=1; i<=100; i++){
if(i % 3 ===0 && i % 5===0){
console.log(i+' fizzBuzz');
} else if(i % 3 ===0){
console.log(i+' fizz');
} else if(i % 5 ===0){
console.log(i+' buzz');
} else {
console.log(i);
}
}
}fizzBuzz();
Slightly different implementation.
You can put your own argument into the function. Can be non-sequential numbers like [0, 3, 10, 1, 4]. The default set is only from 1-15.
function fizzbuzz (set) {
var set = set ? set : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
var isValidSet = set.map((element) => {if (typeof element !== 'number') {return false} else return true}).indexOf(false) === -1 ? true : false
var gotFizz = (n) => {if (n % 3 === 0) {return true} else return false}
var gotBuzz = (n) => {if (n % 5 === 0) {return true} else return false}
if (!Array.isArray(set)) return new Error('First argument must an array with "Number" elements')
if (!isValidSet) return new Error('The elements of the first argument must all be "Numbers"')
set.forEach((n) => {
if (gotFizz(n) && gotBuzz(n)) return console.log('fizzbuzz')
if (gotFizz(n)) return console.log('fizz')
if (gotBuzz(n)) return console.log('buzz')
else return console.log(n)
})
}
var num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var runLoop = function() {
for (var i = 1; i<=num.length; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
}
else if (i % 5 === 0) {
console.log("Buzz");
}
else if (i % 3 === 0) {
console.log("Fizz");
}
else {
console.log(i);
}
}
};
runLoop();
Just want to share my way to solve this
for (i = 1; i <= 100; i++){
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzBuzz');
} else if (i % 3 === 0) {
console.log('fizz');
} else if (i % 5 === 0){
console.log('buzz');
} else {
console.log(i);
}
}
var limit = prompt("Enter the number limit");
var n = parseInt(limit);
var series = 0;
for(i=1;i<n;i++){
series = series+" " +check();
}
function check() {
var result;
if (i%3==0 && i%5==0) { // check whether the number is divisible by both 3 and 5
result = "fizzbuzz "; // if so, return fizzbuzz
return result;
}
else if (i%3==0) { // check whether the number is divisible by 3
result = "fizz "; // if so, return fizz
return result;
}
else if (i%5==0) { // check whether the number is divisible by 5
result = "buzz "; // if so, return buzz
return result;
}
else return i; // if all the above conditions fail, then return the number as it is
}
alert(series);
Thats How i did it :
Not the best code but that did the trick
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(var i = 0 ; i <= 19 ; i++){
var fizz = numbers[i] % 3 === 0;
var buzz = numbers[i] % 5 === 0;
var fizzBuzz = numbers[i] % 5 === 0 && numbers[i] % 3 === 0;
if(fizzBuzz){
console.log("FizzBuzz");
} else if(fizz){
console.log("Fizz");
} else if(buzz){
console.log("Buzz");
} else {
console.log(numbers[i]);
}
}
As much as this is easy logic it can be a daunting task for beginners. Below is my solution to the FizzBuzz problem:
let i = 1;
while(i<=100){
if(i % 3 ==0 && i % 5 == 0){
console.log('FizzBuzz');
}
else if(i % 3 == 0){
console.log('Fizz');
}
else if(i % 5 == 0){
console.log('Buzz');
}
else{
console.log(i);
}
i++;
}
considering performance and readability, please find my take on this problem
way 1: instead of doing a math modules operation in an if loop, which results in performing 3 times taking it a step above reduces the overhead
function fizzBuzz(n) {
let count =0;
let x = 0;
let y = 0;
while(n!==count)
{
count++;
x = count%3;
y = count%5;
if(x === 0 && y ===0)
{
console.log("fizzbuzz");
}
else if(x === 0)
{
console.log("fizz");
}
else if(y === 0)
{
console.log("buzz");
}
else
{
console.log(count);
}
}
}
fizzBuzz(15);
way 2: condensing the solution
function fizzBuzz(n) {
let x = 0;
let y = 0;
for (var i = 1; i <= n; i++) {
var result = "";
x = i%3;
y = i%5;
if (x === 0 && y === 0) result += "fizzbuzz";
else if (x === 0) result += "fizz";
else if (y === 0) result += "buzz";
console.log(result || i);
}
}
fizzBuzz(5)
Here's my favorite solution. Succinct, functional & fast.
const oneToOneHundred = Array.from({ length: 100 }, (_, i) => i + 1);
const fizzBuzz = (n) => {
if (n % 15 === 0) return 'FizzBuzz';
if (n % 3 === 0) return 'Fizz';
if (n % 5 === 0) return 'Buzz';
return n;
};
console.log(oneToOneHundred.map((i) => fizzBuzz(i)).join('\n'));
function fizzBuzz(n) {
for (let i = 1; i < n + 1; i++) {
if (i % 15 == 0) {
console.log("fizzbuzz");
} else if (i % 3 == 0) {
console.log("fizz");
} else if (i % 5 == 0) {
console.log("buzz");
} else {
console.log(i);
}
}
}
fizzBuzz(15);
Different functional style -- naive
fbRule = function(x,y,f,b,z){return function(z){return (z % (x*y) == 0 ? f+b: (z % x == 0 ? f : (z % y == 0 ? b: z))) }}
range = function(n){return Array.apply(null, Array(n)).map(function (_, i) {return i+1;});}
range(100).map(fbRule(3,5, "fizz", "buzz"))
or, to incorporate structures as in above example: ie [[3, "fizz"],[5, "buzz"], ...]
fbRule = function(fbArr,z){
return function(z){
var ed = fbArr.reduce(function(sum, unit){return z%unit[0] === 0 ? sum.concat(unit[1]) : sum }, [] )
return ed.length>0 ? ed.join("") : z
}
}
range = function(n){return Array.apply(null, Array(n)).map(function (_, i) {return i+1;});}
range(100).map(fbRule([[3, "fizz"],[5, "buzz"]]))
OR, use ramda [from https://codereview.stackexchange.com/questions/108449/fizzbuzz-in-javascript-using-ramda ]
var divisibleBy = R.curry(R.compose(R.equals(0), R.flip(R.modulo)))
var fizzbuzz = R.map(R.cond([
[R.both(divisibleBy(3), divisibleBy(5)), R.always('FizzBuzz')],
[divisibleBy(3), R.aklways('Fizz')],
[divisibleBy(5), R.always('Buzz')],
[R.T, R.identity]
]));
console.log(fizzbuzz(R.range(1,101)))

Categories