I'm attempting a Javascript challenge on the 'codewars' website where the instructions are:
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:
likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
For more than 4 names, the number in and 2 others simply increases.
My attempt is this:
function likes(names) {
var response = "a"
console.log(names[0]);
if (names.length === 0) {
response = 'no one likes this';
}
else if (names.length === 1) {
response = names[0] +' likes this';
}
else if (names.length === 2) {
response = names[0] + ' and' + names[1] ' like this';
}
else if (names.length === 3) {
response = names[0] + ',' + names[1] + ' and' + names[2] + ' like this';
}
else {
response = names[0] + ',' + names[1] + ' and' + (names.length-2).toString() + ' others like this';
}
return response;
}
and returns this error:
kata: Unexpected token:44 response = names[0] + ' and' + names[1] ' like this';
is it not possible to concatenate a string value inside an array with another string? Any help would be much appreciated.
You are missing + sign here
response = names[0] + ' and' + names[1] ' like this';
Try like this
response = names[0] + ' and' + names[1] +' like this';
You forgot a + on this line:
response = names[0] + ' and' + names[1] + ' like this';
Not critical but you also forgot a ; and the ' and' should be ' and '
function likes(names) {
var response = "a";
if (names.length === 0) {
response = 'no one likes this';
} else if (names.length === 1) {
response = names[0] + ' likes this';
} else if (names.length === 2) {
response = names[0] + ' and ' + names[1] + ' like this';
} else if (names.length === 3) {
response = names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this';
} else {
response = names[0] + ', ' + names[1] + ' and ' + (names.length - 2).toString() + ' others like this';
}
return response;
}
Related
I want to log when a member has been updated for example a new avatar or nickname. I can log it to a console but when I try to send it to a channel it fails. There are no errors in console. I have tried using multiple accounts and different channels but still no result or any errors in console.
client.on('guildMemberUpdate', async (oldMember, newMember) => {
const guild = newMember.guild;
var Changes = {
unknown: 0,
addedRole: 1,
removedRole: 2,
username: 3,
nickname: 4,
avatar: 5
}
var change = Changes.unknown
var removedRole = ''
oldMember.roles.every(function (value) {
if (newMember.roles.cache.find('id', value.id) == null) {
change = Changes.removedRole
removedRole = value.name
}
})
var addedRole = ''
newMember.roles.every(function (value) {
if (oldMember.roles.cache.find('id', value.id) == null) {
change = Changes.addedRole
addedRole = value.name
}
})
if (newMember.user.username != oldMember.user.username) {
change = Changes.username
}
if (newMember.nickname != oldMember.nickname) {
change = Changes.nickname
}
if (newMember.user.avatarURL() != oldMember.user.avatarURL()) {
change = Changes.avatar
}
var log = guild.channels.cache.get(`755216180603650059`)
if (log != null) {
switch (change) {
case Changes.unknown:
log.send('**[User Update]** ' + newMember)
break
case Changes.addedRole:
log.send('**[User Role Added]** ' + newMember + ': ' + addedRole)
break
case Changes.removedRole:
log.send('**[User Role Removed]** ' + newMember + ': ' + removedRole)
break
case Changes.username:
log.send('**[User Username Changed]** ' + newMember + ': Username changed from ' +
oldMember.user.username + '#' + oldMember.user.discriminator + ' to ' +
newMember.user.username + '#' + newMember.user.discriminator)
break
case Changes.nickname:
log.send('**[User Nickname Changed]** ' + newMember + ': ' +
(oldMember.nickname != null ? 'Changed nickname from ' + oldMember.nickname +
+newMember.nickname : 'Set nickname') + ' to ' +
(newMember.nickname != null ? newMember.nickname + '.' : 'original username.'))
break
case Changes.avatar:
log.send('**[User Avatar Changed]** ' + newMember)
break
}
}
})
Based off Levi_OP's comment
if (a != b) {
//...
}
needs to turn into:
if (a !== b) {
//...
}
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
if (str1 = array B){
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'B000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array C) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'C000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array E) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'E000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array F) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'F000'
print ('Comm_Code = ' + comm_code + '\n')
}
else {
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n')
comm_code = 'D000'
print ('Comm_Code = ' + comm_code + '\n')
}
Hello,
I want to know how to match the string Str1 with the value of the Array B,C,E,F.
I mean :
If Str1 = 800|| 807 || 826 || 847 || 866, Then Comm_code = B000
If Str1 = 827 || 846 then Comm_code = C000
If Str1 = 867 || 879 then Comm_code = E000
If Str1 = 880 || 899 then Comm_code = F000
Else Default --> Comm_code = D000
Please kindly advice.
p.s. : Fyi, I'm using EcmaScript 2015 / ES5.
Just use a simple String.prototype.indexOf:
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
if (B.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'B000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (C.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'C000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (E.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'E000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (F.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'F000';
print ('Comm_Code = ' + comm_code + '\n');
}
else
{
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
comm_code = 'D000';
print ('Comm_Code = ' + comm_code + '\n');
}
You can achieve this with simple if else conditions using Array.indexOf() Methods. However make sure the str1 and the values in the array are of same variable type(string or a number).
if (B.indexOf(str1) > -1 ) { //if value exists in B
//do soemthing;
}
else if(C.indexof(str1) >-1 ) { //if value exists in C
//do soemthing
}
One possible solution to solve this is use Array.some() (I think it is included on ES5 based on this link). First you can create a method that will check if an element is on an array:
function arrayIncludes(arr, ele)
{
return arr.some(function(x) {return (x === ele);});
}
console.log(arrayIncludes([1,2], 2));
console.log(arrayIncludes([1,2], 5));
.as-console {background-color:black !important; color:lime;}
Then, your code can be reworked to this:
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
function arrayIncludes(arr, ele)
{
return arr.some(function(x) {return (x === ele);});
}
if (arrayIncludes(B, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'B000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(C, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'C000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(E, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'E000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(F, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'F000';
print ('Comm_Code = ' + comm_code + '\n');
}
else
{
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
comm_code = 'D000';
print ('Comm_Code = ' + comm_code + '\n');
}
I want to add comma between Haircut and Wash. basically like this: Haircut, Wash And Blow Dry
if(string === 'HaircutWashAndBlowDry'){
string.charAt(0).toUpperCase() + string.slice(1);
str = str.replace(/([A-Z])/g, ' $1').trim();
}
You don't need to lowercase first letter. Use \B along with a simple counter:
var str = 'HaircutWashAndBlowDry';
var i = 1;
console.log(str.replace(/\B([A-Z])/g, function(match, $1) {
return ( i++ == 1 ? ', ' : ' ' ) + $1;
}))
Funny goal :) Let's play a bit with two previous answers (testCase 2 & testCase 3) that relies on words positions and a wider approach that relies on splitting on the And string to behave differently :
// Haircut, Wash And Blow Dry
let strings = [
'HaircutWashAndBlowDry',
'HaircutWashCleanAndBlowDrySet'
];
function testCase1(str) {
let pieces = str.split('And');
pieces[0] = pieces[0].replace(/([a-z])([A-Z])/g, '$1, $2');
pieces[1] = pieces[1].replace(/([a-z])([A-Z])/g, '$1 $2');
return pieces[0] + ' And ' + pieces[1];
}
function testCase2(string) {
return string.replace(/^([A-Z][^A-Z]*)([A-Z])|([A-Z])/g, function($0,$1,$2,$3) {return $2 ? $1 + ", " + $2 : " " + $3 ;});
}
function testCase3(str) {
let i = 1;
return str.replace(/\B([A-Z])/g, function(match, $1) {
return ( i++ == 1 ? ', ' : ' ' ) + $1;
});
}
strings.forEach(str => {
console.log(str);
console.log('testCase1 : ' + testCase1(str));
console.log('testCase2 : ' + testCase2(str));
console.log('testCase3 : ' + testCase3(str));
});
I need help with how to make my code's if else statement to only run once and I was wondering if I followed all the instructions that were asked for this assignment. Also, i may have some errors or placement issues. I am a beginner javascript user as I never used the program before this. The instructions are below as followed:
Run an if/else statement to see if age is less than 60, then display alerts depending on the result
Push a third question to the questions array
Push the corresponding array of answers to the answers array
Add if and else if statements to the score-checking to increment the score at different levels for each answer: 3 points, 2 points, or 1 point depending on the user’s choice. These should be implemented for all three questions. Try to use a for loop to cycle through all the questions and answers, and consider using the index in the array for the scoring system.
-Add <br>Score: plus the user’s score to their paragraph (id='myParagraph') by using document.getElementById to change the innerHTML
Add an additional prompt asking the user to calculate the results of a basic math question
Increment the user’s score by 5 if their answer to the math question is equal to the results of the same math question as an expression: make sure the equation is part of your if statement.
Code below:
var question = ['What is your quest?', 'What is the airspeed of an unladen swallow?', 'What planet\'s moon can more liquid water than all of Earth\'s oceans?'];
var score = 0;
var answers = [
['To seek the grail', 'I don\'t know that', 'To be in Monty Python'],
['African or European?', '92', '24'],
['Europa', 'Titan', 'Pandora']
];
console.log(answers);
console.log(answers[1][0]);
var name = prompt('What is your name?');
//alert('A message;);
document.getElementById('myParagraph').innerHTML = 'Hello ' + name + '!';
document.getElementById('myScore').innerHTML = 'You scored ' + score + 'points!';
console.log(typeof name);
var age = prompt('How old are you?');
console.log(typeof age);
age = Number(age);
console.log(typeof age);
if (age < 60) {
alert(age);
}
for (var i = 0; i <= age; i++) {
document.write(i);
document.write(' ');
}
var math = prompt('What is 16+2-1*3=?');
console.log(typeof math);
math = Number(math);
if (math === 15) {
alert(math);
} else {
alert('You are incorrect');
}
for (var j = 0; j <= math; i + 5) {
document.write(j);
document.write(' ');
}
var guess = prompt(question[0] + '\n\u2022 ' + answers[0][0] + '\n\u2022 ' + answers[0][1] + '\n\u2022 ' + answers[0][2]);
if (guess === answers[0][0]) {
score += 3;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[0][1]) {
score += 2;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[0][2]) {
score += 1;
console.log(score + ' ' + 'points earned!');
}
var guess = prompt(question[1] + '\n\u2022 ' + answers[1][0] + '\n\u2022 ' + answers[1][1] + '\n\u2022 ' + answers[1][2]);
if (guess === answers[1][0]) {
score += 1;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[1][1]) {
score += 2;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[1][2]) {
score += 3;
console.log(score + ' ' + 'points earned!');
}
var guess = prompt(question[2] + '\n\u2022 ' + answers[2][0] + '\n\u2022 ' + answers[2][1] + '\n\u2022 ' + answers[2][2]);
if (guess === answers[2][0]) {
score += 3;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[2][1]) {
score += 2;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[2][2]) {
score += 1;
console.log(score + ' ' + 'points earned!');
}
<br id="myScore">
<p id="myParagraph">A paragraph!</p>
</br>
You have an infinite loop here:
for (var j = 0; j <= math; i + 5) {
document.write(j);
document.write(' ');
}
Since you never modify j, j <= math is always true, so the loop never ends.
I don't see any reason for this loop in the first place. The problem specification says to add 5 to the user's score if they get the math question right. So you should do:
if (math === 15) {
alert(math);
score += 5; // Add 5 to the user's score
} else {
alert('You are incorrect');
}
I have a code for a loto which allows us to find and compare number in a array using loops.I need to update my program so that the work of checking the result is done
by a function called checkNumber. This function should take the customer
number and the array of winning numbers as arguments. The customer number
should be returned from a function called getCustomerNumber. The array of
winning numbers should be returned from a function called
getWinningNumbers. The display of the results should be done by a function
called displayResult(). The whole process should be kicked off by a function
called init. Thank you for your help!
x = checkNumber(12, 17, 24, 37, 38, 43);
function checkNumber() {
for (var i = 0; i < winningNumbers.length && !match ; i++)
if (winningNumbers[i] == customerNumbers) {
match = true;
}
}
}
function getWinningNumbers
function displayResult(){
var message="This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!";
alert(message)
} Else
var message="This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week";
alert(message)
}
}