//push, pop, shift, unshift challenges Part 2: /* Write a function doubleSequence that accepts a base and a length as arguments. The function should return an array representing a sequence that contains "length" elements. The first element of the sequence is always the "base", the subsequent elements can be generated by doubling the previous element of the sequence. */ function doubleSequence(base, length){ if(length === 0){ return []; } let seq = [base] while(seq.length < length){ let last = seq[seq.length - 1]; let next = last * 2; seq.push(next); } return seq; } console.log(doubleSequence(7, 3)); // [7, 14, 28] console.log(doubleSequence(3, 5)); // [3, 6, 12, 24, 48] console.log(doubleSequence(5, 3)); // [5, 10, 20] console.log(doubleSequence(5, 4)); // [5, 10, 20, 40] console.log(doubleSequence(5, 0)); // [ ] /* Write a function tripleSequence that takes in two numbers, start and length. The function should return an array representing a sequence that begins with start and is length elements long. In the sequence, every element should be 3 times the previous element. Assume that the length is at least 1. function tripleSequence(start, length) { let seq = [start]; for (let i = seq.length; i < length; i++) { seq.push(seq[seq.length - 1] * 3); } return seq; } console.log(tripleSequence(2, 4)); // [2, 6, 18, 54] console.log(tripleSequence(4, 5)); // [4, 12, 36, 108, 324] */ /* Write a function unique that accepts an array as an argument. The function should return a new array containing elements of the input array, without duplicates. function unique(arr){ let newArr = [] for(let i = 0; i < arr.length; i++){ let ele = arr[i] if(!newArr.includes(ele)){ newArr.push(ele) } } return newArr; } console.log(unique([1, 1, 2, 3, 3])); // [1, 2, 3] console.log(unique([11, 7, 8, 10, 8, 7, 7])); // [11, 7, 8, 10] console.log(unique(['a', 'b', 'c', 'b'])); // ['a', 'b', 'c'] */ /* Write a function yeller(words) that takes in an array of words. The function should return a new array where each element of the original array is yelled. function yeller(words){ newWords = [] for(let i = 0; i < words.length; i++){ let ele = words[i].toUpperCase() + "!" newWords.push(ele) } return newWords; } console.log(yeller(['hello', 'world'])); // [ 'HELLO!', 'WORLD!' ] console.log(yeller(['kiwi', 'orange', 'mango'])); // [ 'KIWI!', 'ORANGE!', 'MANGO!' ] */ /* Write a function tripler(nums) that takes in an array as an arg. The function should return a new array containing three times every number of the original array. function tripler(nums){ let newNums = [] for(let i = 0; i < nums.length; i++){ let number = nums[i]; newNums.push(number * 3) } return newNums; } console.log(tripler([2, 7, 4])); // [ 6, 21, 12 ] console.log(tripler([-5, 10, 0, 11])); // [ -15, 30, 0, 33 ] */ /* Write a function longWords(words) that takes in an array of words. The function should return an array containing only the words that are longer than 5 characters. function longWords(words){ let newArr = [] for(let i = 0; i < words.length; i++){ let char = words[i] if(char.length > 5){ newArr.push(char) } } return newArr; } console.log(longWords(['bike', 'skateboard','scooter', 'moped'])); // [ 'skateboard', 'scooter' ] console.log(longWords(['couscous', 'soup', 'ceviche', 'solyanka' ,'taco'])); // [ 'couscous', 'ceviche', 'solyanka' ] */ /* Write a function chooseyEndings that accepts an array of words and a suffix string as arguments. The function should return a new array containing the words that end in the given suffix. If the value passed in is not an array, return an empty array. HINT: There are built in JavaScript functions that will help with determining if a strings ends a certain way. Go see if you can find it on MDN! function chooseyEndings(word, suffix){ if(!Array.isArray(word)){ return []; } let selected = [] for(let i = 0; i < word.length; i++){ if(word[i].endsWith(suffix)){ selected.push(word[i]) } } return selected; } console.log(chooseyEndings(['family', 'hound', 'catalyst','fly', 'timidly', 'bond'], 'ly')); // [ 'family', 'fly', 'timidly' ] console.log(chooseyEndings(['family', 'hound', 'catalyst','fly', 'timidly', 'bond'], 'nd')); // [ 'hound', 'bond' ] console.log(chooseyEndings(['simplicity', 'computer', 'felicity'], 'icity')); // [ 'simplicity', 'felicity' ] console.log(chooseyEndings(['simplicity', 'computer', 'felicity'], 'ily')); // [ ] console.log(chooseyEndings(17, 'ily')); // [ ] */ /* Write a function commonFactors that accepts two numbers as arguments. The function should return an array containing positive numbers that are able to divide both arguments. function commonFactors(num1, num2){ let factors = []; for(let i = 0; i <= num1; i++){ if(num1 % i === 0 && num2 % i === 0){ factors.push(i) } } return factors; } console.log(commonFactors(50, 30)); // [1, 2, 5, 10] console.log(commonFactors(8, 4)); // [1, 2, 4] console.log(commonFactors(4, 8)); // [1, 2, 4] console.log(commonFactors(12, 24)); // [1, 2, 3, 4, 6, 12] console.log(commonFactors(22, 44)); // [1, 2, 11, 22] console.log(commonFactors(7, 9)); // [1] */ /* Write a function adjacentSums that accepts an array of numbers as an argument. The function should return a new array containing the sum of each pair of elements in the input array. function adjacentSums(arr){ adjacents = [] for(let i = 0; i < arr.length - 1; i++){ sum = arr[i] + arr[i + 1] adjacents.push(sum) } return adjacents; } console.log(adjacentSums([3, 8, 7, 1])); // [ 11, 15, 8 ] console.log(adjacentSums([10, 5, 4, 3, 9])); // [ 15, 9, 7, 12 ] console.log(adjacentSums([2, -3, 3])); // [-1, 0] */ /* Write a function pickPrimes that takes in an array of numbers and returns a new array containing only the prime numbers. function isPrimes(num){ if(num < 2){ return false; } for(let i = 2; i < num; i++){ if(num % i === 0){ return false; } } return true; } function pickPrimes(arr){ let primes = [] for(let i = 0; i < arr.length; i++){ if(isPrimes(arr[i])){ primes.push(arr[i]) } } return primes; } console.log(pickPrimes([2, 3, 4, 5, 6])); // [2, 3, 5] console.log(pickPrimes([101, 20, 103, 2017])); // [101, 103, 2017] */ /* Write a function greatestFactorArray that takes in an array of numbers and returns a new array where every even number is replaced with it's greatest factor. A greatest factor is the largest number that divides another with no remainder. For example, the greatest factor of 16 is 8. (For the purpose of this problem we won't say the greatest factor of 16 is 16, because that would be too easy). function greatestFactorArray(array) { let new_array = []; for (let i = 0; i < array.length; i++) { if (array[i] % 2 == 0) { new_array.push(greatestFactor(array[i])); } else { new_array.push(array[i]); } } return new_array; } function greatestFactor(num) { for (let i = num-1; i > 0; i--) { if (num % i == 0) { return i; } } } console.log(greatestFactorArray([16, 7, 9, 14])); // [8, 7, 9, 7] console.log(greatestFactorArray([30, 3, 24, 21, 10])); // [15, 3, 12, 21, 5] */ /* A number's summation is the sum of all positive numbers less than or equal to the number. For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a function summationSequence that takes in two numbers: start and length. The function should return an array containing length total elements. The first number of the sequence should be the start number. At any point, to generate the next element of the sequence we take the summation of the previous element. You can assume that length is not zero. function summationSequence(start, length) { // your code here let sequence = [start] for(let i = sequence.length; i < length; i++){ sequence.push(summation(sequence[sequence.length - 1])) } return sequence; } function summation(num){ total = 0; for(let i = 1; i <= num; i++){ total += i; } return total; } console.log(summationSequence(3, 4)); // [3, 6, 21, 231] console.log(summationSequence(5, 3)); // [5, 15, 120] */ //Who's Buying Lunch? Code Challenge: function whosPaying(names) { let numOfPeople = names.length; let randomPersonPosition = Math.floor(Math.random() * numOfPeople); randomPerson = names[randomPersonPosition] return randomPerson; } console.log(whosPaying(["Angela", "Ben", "Jenny", "Michael", "Chloe"]))
Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.
Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log("Hello, " + line);
});
Keyword | Description | Scope |
---|---|---|
var | Var is used to declare variables(old way of declaring variables) | Function or global scope |
let | let is also used to declare variables(new way) | Global or block Scope |
const | const is used to declare const values. Once the value is assigned, it can not be modified | Global or block Scope |
let greetings = `Hello ${name}`
const msg = `
hello
world!
`
An array is a collection of items or values.
let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);
let mobiles = ["iPhone", "Samsung", "Pixel"];
// accessing an array
console.log(mobiles[0]);
// changing an array element
mobiles[3] = "Nokia";
Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.
() => expression
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
.map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);
let [firstName, lastName] = ['Foo', 'Bar']
let {firstName, lastName} = {
firstName: 'Foo',
lastName: 'Bar'
}
const {
title,
firstName,
lastName,
...rest
} = record;
//Object spread
const post = {
...options,
type: "new"
}
//array spread
const users = [
...adminUsers,
...normalUsers
]
function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
console.log(`Hello ${name}!`);
}
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar
IF is used to execute a block of code based on a condition.
if(condition){
// code
}
Else part is used to execute the block of code when the condition fails.
if(condition){
// code
} else {
// code
}
Switch is used to replace nested If-Else statements.
switch(condition){
case 'value1' :
//code
[break;]
case 'value2' :
//code
[break;]
.......
default :
//code
[break;]
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while (condition) {
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.
class className {
constructor() { ... } //Mandatory Class method
method1() { ... }
method2() { ... }
...
}
class Mobile {
constructor(model) {
this.name = model;
}
}
mbl = new Mobile("iPhone");