Skip to content

Instantly share code, notes, and snippets.

@OdearOgy
Created August 6, 2018 19:16
Show Gist options
  • Save OdearOgy/93b6b5b0957a83cde9bf6e4a6ca4eaa6 to your computer and use it in GitHub Desktop.
Save OdearOgy/93b6b5b0957a83cde9bf6e4a6ca4eaa6 to your computer and use it in GitHub Desktop.
JavaScript code and simple algorithms
for (var i = 0; i < contacts.length; i++) {
for (var j = 0; j < contacts[i].length; j++) {
console.log(contacts[i][j]);
}
if (contacts.hasOwnProperty(firstName) || contacts.hasOwnProperty(prop)) {
return contacts.prop;
} else if (contacts.hasOwnProperty(firstName) !== true) {
return "No shuch contact"
} else if (contacts.hasOwnProperty(prop) !== true) {
return "No such property";
}
} return contacts;
//մի օր բզբզալ, աշխատացնել, ստուգել այս կոդը, որը քո հրաշք ուղեղը հորինեց
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var humanBeing = 0; humanBeing < contacts.length; humanBeing++) {
if (contacts[humanBeing].firstName === firstName ) {
if (contacts[humanBeing].hasOwnProperty(prop)) {
return contacts[humanBeing][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
//ստուգել սա նույնպես
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
//cool stuff
// Setup
var testString = "Ada Lovelace and Charles Babbage designed the first computer and the software that would have run on it.";
// Example
var expressionToGetSoftware = /software/gi;
var softwareCount = testString.match(expressionToGetSoftware).length;
// Only change code below this line.
var expression = /and/gi; // Change this Line
// Only change code above this line
// This code counts the matches of expression in testString
var andCount = testString.match(expression).length;
//yeaaah
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
var Bike = function() {
var gear = 6;
this.getGear = function() {
return gear;
};
this.setGear = function(change) {
gear = change;
};
// Only change code below this line.
};
var myCar = new Car();
var myBike = new Bike();
//tuyn
//array.reduce
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
singleVal = array.reduce(function (a, b) {
return a + b;
}, 0);
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
//tuyn
// short with arrow function
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( acc, cur ) => acc.concat(cur),
[]
);
// friends - an array of objects
// where object field "books" - list of favorite books
var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
return [...prev, ...curr.books];
}, ['Alphabet']);
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
//check tree dots on return
// նոր մասիվի մեջ ա գցում 6-ից փոքր հին մասիվի բոլոր տարրերը
var oldArray = [1,2,3,4,5,6,7,8,9,10];
// Only change code below this line.
var newArray = oldArray.filter(function (arr) {
return arr < 6;
});
function palindrome(str) {
// Good luck!
// if (str.split(" ").reverse().join("") === str) {
// str = str.replace(/[\W_]/g, "").toLowerCase();
// return true;
// } else {
// return false;
// }
// var itr = str.toLowerCase();
// var varSplit = itr.split(" ");
// var varJoin = varSplit.join("");
// var repVar = varJoin.replace("/\r\n|\r|\n/" , '');
// return repVar;
// var itr = str.toLowerCase();
// var varSplit = itr.split(" ");
// var varJoin = varSplit.join("");
// var repVar = varJoin.replace(/\,/g, "").replace(/\./g, "");
// return true;
var varSplit = str.split(" ").join("").toLowerCase().replace(/[\W_]/g, "").replace(/[\W_]/g, ""),
true_str = varSplit.split("").reverse().join("");
if(varSplit === true_str){
return true;
}
else{
return false;
}
}
palindrome("A man, a plan, a camal. Panama");
//check this, try to explain to yourself
function palindrome(str) {
return str.replace(/[\W_]/g, '').toLowerCase() ===
str.replace(/[\W_]/g, '').toLowerCase().split('').reverse().join('');
}
//check this too
function palindrome(str) {
str = str.toLowerCase().replace(/[\W_]/g, '');
for(var i = 0, len = str.length - 1; i < len/2; i++) {
if(str[i] !== str[len-i]) {
return false;
}
}
return true;
}
//same problem
function findLongestWord(str) {
var strArr = str.split(" ");
var emptyArr = [];
for (var i = 0; i < strArr.length; i++) {
emptyArr.push(strArr[i].length);
}
return Math.max(...emptyArr);
}
findLongestWord("The quick brown fox jumped over the lazy dog");
//same idea
function findLongestWord(str) {
var strArr = str.split(" ");
var retVal = 0;
for (var i = 0; i < strArr.length; i++) {
if (strArr[i].length > retVal) {
retVal = strArr[i].length;
}
}
return retVal;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function titleCase(str) {
// var arrStr = str.toLowerCase().split(" ");
// var newArr = arrStr.replace(arrStr.charAt(0), arrStr.toUpperCase());
// var newVal = arrStr.replace(arrStr.charAt(0), arrStr.toUpperCase());
// var retVal = 0;
// for (var i = 0; i < arrStr.length; i++) {
// function repWord( str )
// {
// return str2.join(" ");
// }
// console.log(repWord("sunday monday tuesday wednesday"))
// }
var arrStr = str.split(" ");
for (var i = 0; i < arrStr.length; i++) {
var j = arrStr[i].charAt(0).toUpperCase();
arrStr[i] = j + arrStr[i].substr(1).toLowerCase();
}
return arrStr.join(" ");
}
titleCase("I'm a little tea pot");
//
function titleCase(str) {
var convertToArray = str.toLowerCase().split(" ");
var result = convertToArray.map(function(val){
return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
});
return result.join(" ");
}
titleCase("I'm a little tea pot");
//
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}
function largestOfFour(arr) {
// You can do this!
var smArr = arr;
var emptyArr = [];
for (var i = 0; i < smArr.length; i++) {
var arrVal = 0;
for (var j = 0; j < smArr[i].length; j++) {
if (smArr[i][j] > arrVal) {
arrVal = smArr[i][j];
}
}
emptyArr.push(arrVal);
}
return emptyArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//returning the largest elements of an array, very simple and cool :)
function largestOfFour(arr) {
let newArr = [];
arr.forEach((a) => {
newArr.push(Math.max.apply(null, a));
});
return newArr;
}
//check this one
function largestOfFour(arr) {
return arr.map(function(group){
return group.reduce(function(prev, current) {
return (current > prev) ? current : prev;
});
});
}
//
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
}
results[n] = largestNumber;
}
return results;
}
//
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
//
// if (str.endsWith(target)) {
// return true;
// } else {
// return false;
// }
}
confirmEnding("Bastian", "n");
//code check's ending of string ...
array split to sub arrays
function grouper(array, cols) {
function split(array, cols) {
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));
}
var a = split(array, cols);
var groups = [];
var group = [];
for(var i = 0; i < a.length; i++) {
if (a[i] === null) {
groups.push(group);
group = [];
continue;
}
group.push(a[i]);
}
groups.push(group);
return groups;
}
var test1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(grouper(test1, 2));
console.log(grouper(test1, 3));
console.log(grouper(test1, 4));
function chunkArrayInGroups(arr, size) {
// Break it up.
// var newArr = arr.slice(0, size);
var i = 0;
var emptyArr = [];
var newArr = Math.ceil(arr.length / size);
while (i < newArr) {
i++;
emptyArr.push(arr.slice(0, size));
}
return emptyArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
function grouper(array, cols) {
function split(array, cols) {
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));
}
var a = split(array, cols);
var groups = [];
var group = [];
for(var i = 0; i < a.length; i++) {
if (a[i] === null) {
groups.push(group);
group = [];
continue;
}
group.push(a[i]);
}
groups.push(group);
return groups;
}
var test1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(grouper(test1, 2));
console.log(grouper(test1, 3));
console.log(grouper(test1, 4));
function chunk (arr, len) {
var a = Math.round(arr.length/len),
array = [],
i =0;
while(i < len){
array.push(arr.splice(0, a));
if(array[array.length-1] ==""){
array[array.length-1] = array[array.length-2].splice(0,1)
}
i++;
}
return array;
}
console.log(chunk(["a", "b", "c", "d", "e", "f", "g", "h"], 5));
//CODE without slice
function chunkArrayInGroups(arr, size) {
var temp = [];
var result = [];
for (var a = 0; a < arr.length; a++) {
if (a % size !== size - 1) temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0) result.push(temp);
return result;
}
chunkArrayInGroups(['a', 'b', 'c', 'd'], 4);
//
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0,size));
}
return newArr;
}
//հանրահաշվական պրոգրեսիա
// function aritGeo(aritArray = []){
// i=0;
// for(i=0; i<aritArray.length; i++){
// if((aritArray[i+1]-aritArray[i])===(aritArray[i+2]-aritArray[i+1])){
// return 'arithmetic progression';
// }
// else{
// return 'not an arithmetic progression';
// }
// }
// }
aritGeo([5,7,9,11,14]);
// // function aritGeo2(aritArray2=[]){
// // let i=0;
// // let answer;
// // let d = aritArray2[1]-aritArray2[0];
// // while((aritArray2[i+1]-aritArray2[i])===d && i<=aritArray2.length){
// // answer = 'Arithmetic progression';
// // i++;
// // }
// // return answer;
// // }
aritGeo2([5,7,9,11,14]);
function arithmeticProgress (a,b,c,d,e) {
let answer;
if ((5*(a + e))/2) {
answer = true;
} else {
answer = false;
}
return answer;
}
arithmeticProgress(5,7,9,11,14);
const fib = n => {
if(n <= 1) {
return 1;
}
return fib(n-1) + fib(n-2);
}
// fibonacci
const fibonacci = n => n<=1 ? 1: fibonacci(n-1) + fibonacci(n-2);
console.log(fibonacci(8));
const printStarLine = n => {
if (n <= 0) {
return "Wrong Number";
}
if (n === 1) {
return "*\n";
}
let starr = "";
for (let i = 0; i < n; i++) {
starr += "*";
}
return printStarLine(n-1) + starr + "\n" ;
}
console.log(printStarLine(6));
//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
//creating a new paragraph
var p = document.createElement("p");
var node = document.createTextNode("Some new text");
//adding the text to the paragraph
p.appendChild(node);
var head1 = document.createElement("h1");
var node1 = document.createTextNode("Cool Header");
head1.appendChild(node1);
var div = document.getElementById("demo");
//adding the paragraph to the div
div.appendChild(p);
div.insertBefore(head1, div.firstChild);
};
const range = (numA, numB) => {
// !RECURSION!
// The program must take two numbers as arguments
// It should return an array of numbers between numA and numB
// (the array should not include numA and numB)
if (numA > numB) {
return range(numB, numA);
}
if (numB - numA === 1 || numA === numB) {
return [];
}
// return --numB + range(numA, numB);
return [numA + 1, ...range(numA + 1, numB)];
}
if (numA === numB) {
return 0;
}
const sign = numA > numB ? -1 : 1;
if (numA + sign === numB) {
return [];
}
if (sign === 1) {
return [numA + sign, ...range(numA + sign, numB)]
} else {
return [ ...range(numA + sign, numB), numA + sign];
}
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
// Our array of messy words
var capitals = ["berlin", "parIs", "MaDRiD"];
// Capitalize function
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
// Our recursive function
function fixLetterCase(array, i) {
// Base case
if (i === array.length) {
return;
}
// Action
array[i] = capitalize(array[i]);
// Recursive case
return fixLetterCase(array, i + 1);
}
// Here is our function call
fixLetterCase(capitals, 0);
console.log(capitals);
function rot13(str) {
// Split str into a character array
return str.split('')
// Iterate over each character in the array
.map.call(str, function(char) {
// Convert char to a character code
x = char.charCodeAt(0);
// Checks if character lies between A-Z
if (x < 65 || x > 90) {
return String.fromCharCode(x); // Return un-converted character
}
//N = ASCII 78, if the character code is less than 78, shift forward 13 places
else if (x < 78) {
return String.fromCharCode(x + 13);
}
// Otherwise shift the character 13 places backward
return String.fromCharCode(x - 13);
}).join(''); // Rejoin the array into a string
}
function rot13(str) {
var rotCharArray = [];
var regEx = /[A-Z]/ ;
str = str.split("");
for (var x in str) {
if (regEx.test(str[x])) {
// A more general approach
// possible because of modular arithmetic
// and cyclic nature of rot13 transform
rotCharArray.push((str[x].charCodeAt() - 65 + 13) % 26 + 65);
} else {
rotCharArray.push(str[x].charCodeAt());
}
}
str = String.fromCharCode.apply(String, rotCharArray);
return str;
}
// Change the inputs below to test
rot13("LBH QVQ VG!");
function rot13(str) { // LBH QVQ VG!
return str.replace(/[A-Z]/g, decFunc => String.fromCharCode((decFunc.charCodeAt(0) % 26) + 65));
}
git remote add <someName> github repo link
git remote -v
// The Babylonian Method
// http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
// @param n - the number to compute the square root of
// @param g - the best guess so far (can omit from initial call)
function squirt(n, g) {
if (!g) {
// Take an initial guess at the square root
g = n / 2.0;
}
var d = n / g; // Divide our guess into the number
var ng = (d + g) / 2.0; // Use average of g and d as our new guess
if (g == ng) {
// The new guess is the same as the old guess; further guesses
// can get no more accurate so we return this guess
return g;
}
// Recursively solve for closer and closer approximations of the square root
return squirt(n, ng);
}
console.log(squirt(42)); // 6.48074069840786
//"algorithm for calculating square root
const root = (a, pow) => {
return a ** (pow ** -1);
}
//another one
function squareroot(number) {
for (var i = 0; i * i <= number; i++) {
if (i * i === number)
return i;
}
return number; // don't know if you should have this line in case nothing found
}
//and with while loop
function squareroot(number) {
var lo = 0, hi = number;
while(lo <= hi) {
var mid = Math.floor((lo + hi) / 2);
if(mid * mid > number) hi = mid - 1;
else lo = mid + 1;
}
return hi;
}
//Newton's method
function newton(f, fPrime, tolerance) {
var x, first;
return function iterate(n) {
if (!first) { x = n; first = 1; }
var fn = f(x);
var deltaX = fn(n) / fPrime(n);
if (deltaX > tolerance) {
return iterate(n - deltaX)
}
first = 0;
return n;
}
}
function f(n) {
return function(x) {
if(n < 0) throw n + ' is outside the domain of sqrt()';
return x*x - n;
};
}
function fPrime(x) {
return 2*x;
}
var sqrt = newton(f, fPrime, .00000001)
console.log(sqrt(2))
console.log(sqrt(9))
console.log(sqrt(64))
//find sequence
function findSequence(goal) {
function find(start, history) {
if (start == goal) {
return history;
}
else if (start > goal) {
return null;
}
else {
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
}
return find(1, "1");
}
findSequence(24);
//ավելի երկար, բայց բացատրվող տարբերակ
else {
var found = find(start + 5, "(" + history + " + 5)");
if (found == null)
found = find(start * 3, "(" + history + " * 3)");
return found;
}
function catNames(paragraph) {
var colon = paragraph.indexOf(":");
return paragraph.slice(colon + 2).split(", ");
}
catNames("born 20/09/2004 (mother Yellow Bess): Doctor Hobbles the 2nd, Noog");
//todays forecast in Kelvin
const kelvin = prompt("what is the Kelvin temperature today?");
//converting Kelvin to Celsius
let celsius = kelvin - 273;
//geting degrees in Fahrenheit, and rounding it
let fahrenheit = Math.floor(celsius * (9/5) + 32);
//printing temperature in fahrenheit
console.log(`The tempereature is ${fahrenheit} degrees fahrenheit`);
function add(number, howmuch) {
if (arguments.length < 2) {
howmuch = 1;
}
return number + howmuch;
}
add(6); //7
add(6, 4); //10
function range(start, end) {
if (arguments.length < 2) {
end = start;
start = 0;
}
let result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}
range(4); // [0, 1, 2, 3, 4]
range(2, 4); // [2, 3, 4]
function sum(numbers) {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
sum(range(1, 10));
//range is a function created above
function multiply(numbers) {
let total = 1;
for (let i = 1; i < numbers.length; i++) {
total *= numbers[i];
}
return total;
}
multiply(range(1, 5)); //outputs 120! some kind of fatorial function
// range is a function described above
function between(string, start, end) {
let startAt = string.indexOf(start) + start.length;
let endAt = string.indexOf(end, startAt);
return string.slice(startAt, endAt);
}
between("Louis \"Pops\" Armstrong", "\"", "\"");
function foo(){
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
alert(foo());
//outputs 8
var a = 1;
function b() {
// Hoisted
function a() {}
a = 10;
return;
}
b();
console.log(a)
//outputs 1
function parent() {
var hoisted = "I'm a variable"; // and this
function hoisted() {
return "I'm a function";
}
return hoisted(); //because of this and
}
console.log(parent());
//output: "TyperError: hoisted is not a function
alert(foo());
function foo() {
var bar = function() {
return 3;
};
return bar();
var bar = function() {
return 8;
};
}
//outputs 3
var myVar = 'foo';
(function() {
console.log('Original value was: ' + myVar);
var myVar = 'bar';
console.log('New value is: ' + myVar);
})();
//output: "Original value was: undefined" "New value is: bar";
function lastElement(array) {
if (array.length > 0) {
return array[array.length - 1];
}
else {
return undefined;
}
}
lastElement([1, 2, undefined]);
// if the last element is not a string and it with
// a typo like "undeined", it will throw an error: "last element with the typo"
// is not defined
// why the hell, I don't know yet
function lastElement1(array) {
if (array.length > 0) {
return array[array.length - 1];
}
else {
throw "Cannot take the last element of an empty array";
}
}
function lastElement1PlusTen(array) {
return lastElement1(array) + 10;
}
try {
console.log(lastElement1PlusTen([]));
}
catch (error) {
console.log("Something went wrong: ", error);
}
// this worked in browser, but didn't in node
//try-catch...
function processThing(thing) {
let prevThing = currentThing;
currentThing = thing;
try {
//do something complicated or cool
}
finally {
currentThing = prevThing;
}
}
for (;;) {
try {
alert(inputNumber() + 5);
break;
}
catch (e) {
alert("You did not input a number. Try again.");
}
}
//infinite catch
let invalidInputError = new Error("Invalid numeric input");
function inputNumber() {
let = Number(prompt("Give me a number", ""));
if(isNaN(input)) {
throw invalidInputError;
}
return input;
}
try {
alert(inputNumber() + 5);
break;
}
catch (e) {
if (e !== invalidInputError) {
throw e;
}
alert("You did not input a number. Try again.");
}
// play with this code too
let person = {
_name: 'Lu Xun',
_age: 137,
set age(newAge) {
if (typeof newAge === 'number') {
this._age = newAge;
console.log("It's a valid input");
} else {
console.log('Invalid input');
}
}
};
person.age = 'Thirty-nine';
person.age = 39;
//check this code with \"\" instead of \'\'
const obj = {
elements: [0,1,2,3,4,5,6,7,8,9],
exponent: 2,
calc: function(){
return this.elements.map( e => e ** this.exponent);
}
};
console.log(obj.calc()); // [0,1,4,9,16,25,36,49,64,81]
console.log(obj.calc.call({
exponent: 3,
elements: obj.elements
}));
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: () => {
console.log('Inside `bar`:', this.foo);
}
};
}
createObject.call({foo: 21}).bar();
// Inside `createObject`: 21
// Inside `bar`: 21
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: function() {
console.log('Inside `bar`:', this.foo);
}
};
}
createObject.call({foo: 21}).bar();
// Inside `createObject`: 21
// Inside `bar`: 42
var o = {
a: 2,
m: function() {
return this.a + 1;
}
};
console.log(o);
var p = Object.create(o);
p.a = 4;
console.log(p);
function myMap() {
var mapOptions = {
center: new google.maps.LatLng(51.5, -0.12),
zoom: 10,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
{
function foo () { return 1 }
foo() === 1
{
function foo () { return 2 }
foo() === 2
}
foo() === 1
}
let odds = evens.map(v => v + 1);
let pairs = evens.map(v => ({ even: v, odd: v + 1 }));
let nums = evens.map((v, i) => v + i);
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
//es6
this.nums.forEach((v) => {
if (v % 5 === 0)
this.fives.push(v)
})
//es5
// variant 1
var self = this;
this.nums.forEach(function (v) {
if (v % 5 === 0)
self.fives.push(v);
});
// variant 2
this.nums.forEach(function (v) {
if (v % 5 === 0)
this.fives.push(v);
}, this);
// variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
if (v % 5 === 0)
this.fives.push(v);
}.bind(this));
//es5 default parameters
function f (x, y, z) {
if (y === undefined)
y = 7;
if (z === undefined)
z = 42;
return x + y + z;
};
f(1) === 50;
//es6 default parameters;
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
//es5 rest parameters
function f (x, y) {
var a = Array.prototype.slice.call(arguments, 2);
return (x + y) * a.length;
};
f(1, 2, "hello", true, 7) === 9;
//es6 rest parameters;
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, "hello", true, 7) === 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment