if (jsExpression) { console.log('this expression is true'); }
// this expression is false if (jsExpression) { console.log('this expression is true'); } else { console.log('this expression is false'); }
// this expression is false and the firstNmumber is greater than 0 if (jsExpression) { console.log('this expression is true'); } elseif (firstNumber > 0) { console.log('this expression is false and the firstNmumber is greater than 0'); } else { console.log('this expression is false and the firstNmumber is 0 or less'); }
if (randomColor === 'orange') { console.log('the color is orange'); } elseif (randomColor === 'green') { console.log('the color is green'); } elseif (randomColor === 'yellow') { console.log('the color is yellow'); } elseif (randomColor === 'purple') { console.log('the color is purple'); } elseif (randomColor === 'blue') { console.log('the color is blue'); } else { console.log('the color is not found'); }
//swith case statement
switch (randomColor) { case'orange': console.log('the color is orange'); break; case'green': console.log('the color is green'); break; case'yellow': console.log('the color is yellow'); break; case'purple': console.log('the color is purple'); break; case'blue': console.log('the color is blue'); break; default: console.log('the color is not found'); break; }
// Complete the solution so that it reverses the string passed into it. functionsolution(str){ return str.split('').reverse().join(''); }
//Return the number (count) of vowels in the given string. //We will consider a, e, i, o, u as vowels //The input string will only consist of lower case letters and/or spaces.
functiongetCount(str) { let result = 0; const vowels = ['a', 'e', 'i', 'o', 'u']; for(let i =0; i < vowels.length; i++){ result += str.split(vowels[i]).length-1; } return result; }
functiongetCount1(str) { var vowelsCount = 0; var vowels = ["a","e","i","o","u"]; for(var i = 0;i < str.length;i++){ for(var j=0;j<vowels.length;j++){ if(str[i] === vowels[j]){ vowelsCount++; } } } return vowelsCount; }
// Given an array of integers your solution should find the smallest integer.the supplied array will not be empty.
classSmallestIntegerFinder { findSmallestInt(args) { let result = args[0]; for(let i = 1; i < args.length; i++){ if(result > args[i]){ result = args[i]; } } return result; } }
//Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. var summation = function (num) { let sum = 0; for(let i = num; i > 0; i--){ sum += i; } return sum; }
//The Math.floor() method rounds a number DOWN to the nearest integer.
//create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry about strings with less than two characters.
functionremoveChar(str){ let result = ''; for (let index = 1; index < str.length - 1; index++) { result += str[index]; } return result; };
//You get an array of numbers, return the sum of all of the positives ones. //Example [1,-4,7,12] => 1 + 7 + 12 = 20 functionpositiveSum(arr) { let sum = 0; for (let num of arr) { if(num >= 0) { sum += num; } } return sum; }
//Your task is to create a function that does four basic mathematical operations. //The function should take three arguments - operation(string/char), value1(number), value2(number). //The function should return result of numbers after applying the chosen operation.
eval(value1+operation+value2) //Write a function to split a string and convert it into an array of words. functionstringToArray(string){ return string.split(' '); }
//Write a function that removes the spaces from the string, then return the resultant string. let removedSpacesText = originalText.split(" ").join("");
let originalText = "Geeks for Geeks Portal"; let removedSpacesText1 = originalText.replace(/ /g, "");
functionmaps(x){ //return x.map(el => el * 2); let arr = []; for(let i = 0; i < x.length; i++){ arr.push(x[i] * 2); } return arr; }
//get the sum of two arrays... Actually the sum of all their elements. functionarrayPlusArray(arr1, arr2) { let arr = [...arr1, ...arr2]; return arr.reduce((a, b) => a + b); }
//The first century spans from the year 1 up to and including the year 100, the second century - from the year 101 up to and including the year 200, etc. functioncentury(year) { returnMath.ceil(year/100); //using ceiling method to round up to nearest century (100) }
//I have a cat and a dog.
//I got them at the same time as kitten/puppy. That was humanYears years ago.
//Return their respective ages now as [humanYears,catYears,dogYears] var humanYearsCatYearsDogYears = function(humanYears) { let catYears = 0; let dogYears = 0; if(humanYears >= 1) { catYears += 15; dogYears += 15; } if(humanYears >= 2) { catYears += 9; dogYears += 9; } if(humanYears >= 3) { catYears += (humanYears-2)*4 dogYears += (humanYears-2)*5 }
// Our football team has finished the championship.
// Our team's match results are recorded in a collection of strings. Each match is represented by a string in the format "x:y", where x is our team's score and y is our opponents score.
// For example: ["3:1", "2:2", "0:1", ...]
// Points are awarded for each match as follows:
// if x > y: 3 points (win) // if x < y: 0 points (loss) // if x = y: 1 point (tie) // We need to write a function that takes this collection and returns the number of points our team (x) got in the championship by the rules given above.
Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.
replaceAll(pattern, replacement)
returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
If pattern is a regex, then it must have the global (g) flag set, or a TypeError is thrown.
1 2 3 4 5 6 7 8 9
const paragraph = "I think Ruth's dog is cuter than your dog!";
console.log(paragraph.replaceAll('dog', 'monkey')); // Expected output: "I think Ruth's monkey is cuter than your monkey!"
// Global flag required when calling replaceAll with regex const regex = /Dog/gi; console.log(paragraph.replaceAll(regex, 'ferret')); // Expected output: "I think Ruth's ferret is cuter than your ferret!"
toUpperCase()
The toUpperCase() method of String values returns this string converted to uppercase.
trim()
The trim() method of String values removes whitespace from both ends of this string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().
returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
element The current element being processed in the array.
index The index of the current element being processed in the array.
creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
callbackFn A function to execute for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise.
1 2 3 4 5 6
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
callbackFn Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce().
accumulator The value resulting from the previous call to callbackFn. On the first call, its value is initialValue if the latter is specified; otherwise its value is array[0].
currentValue The value of the current element. On the first call, its value is array[0] if initialValue is specified; otherwise its value is array[1].
currentIndex The index position of currentValue in the array. On the first call, its value is 0 if initialValue is specified, otherwise 1.
creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const strPrim = "foo"; // A literal is a string primitive const strPrim2 = String(1); // Coerced into the string primitive "1" const strPrim3 = String(true); // Coerced into the string primitive "true" const strObj = newString(strPrim); // String with new returns a string wrapper object.
//A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the UNIX epoch). This timestamp is timezone-agnostic and uniquely defines an instant in history.
const myDate = newDate(); // new Date() // new Date(value) // new Date(dateString) // new Date(dateObject)
// new Date(year, monthIndex)
//monthIndex Integer value representing the month, beginning with 0 for January to 11 for December. // new Date(year, monthIndex, day) // new Date(year, monthIndex, day, hours) // new Date(year, monthIndex, day, hours, minutes) // new Date(year, monthIndex, day, hours, minutes, seconds) // new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
// Date()
const today = newDate(); const birthday1 = newDate("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes const birthday2 = newDate("1995-12-17T03:24:00"); // This is standardized and will work reliably const birthday3 = newDate(1995, 11, 17); // the month is 0-indexed const birthday4 = newDate(1995, 11, 17, 3, 24, 0); const birthday5 = newDate(628021800000); // passing epoch timestamp
const event = newDate('05 October 2011 14:48 UTC'); console.log(event.toString()); // Expected output: "Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)" // Note: your timezone may vary
const re = /ab+c/i; // literal notation // OR const re = newRegExp("ab+c", "i"); // constructor with string pattern as first argument // OR const re = newRegExp(/ab+c/, "i"); // constructor with regular expression literal as first argument
// best practices functionarray_diff(a, b) { return a.filter(e => !b.includes(e)); }
//You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
functionisValidWalk(walk) { var dx = 0 var dy = 0 var dt = walk.length for (var i = 0; i < walk.length; i++) { switch (walk[i]) { case'n': dy--; break case's': dy++; break case'w': dx--; break case'e': dx++; break } } return dt === 10 && dx === 0 && dy === 0 }
//Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
//39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit) //999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2) //4 --> 0 (because 4 is already a one-digit number)
functionpersistence(num) { var times = 0; num = num.toString(); while (num.length > 1) { times++; num = num.split('').map(Number).reduce((a, b) => a * b).toString(); } return times; }
//count the total number of lowercase letters in a string.