let x = () => {x + 2}
let x = (x,y) => ({object})
// default values:
func doSmth(param = {prop: value}, prop2: "val") {...}
let dinner = "dinner"
mealPlan = {
dinner // shorthand of dinner: "dinner"
}
let o5 = ({prop}) => ({prop: prop ? 1 : 0, prop2: prop})
o5({prop})
let ob = {prop1: 1, prop2: 2, prop3: 3}
const pr = ({prop1, prop2}) => ({
prop1,
prop2: prop2 ? true : false
})
pr(ob);
// deconstructing obj
var {prop1, prop3: newName} = {prop1: 1, prop2: 2, prop3: 3}
console.log(prop3, newName)
let name = "name", surname = "surname";
let data = { surname, prop1: "prop1", propSur: surname, propInt: 4};
const renameProps = ({prop1: name}) => ({ name, prop1: name});
renameProps(data)
// {name: "prop1", prop1: "prop1"}
// -----------------
function xyz( { weight, height: h, max = 25, callback}) {
weight * h....
}
xyz({weight, height, max: 30});
xyz({weight, height, callback: function() {} });
// -----------------
var restaurants = [
{
cuisine: "Pizza",
name: "Kubo"
}, {
cuisine: "Burger",
name: "Fuj"
}
]
const isBurger = ({cuisine}) => cuisine === 'Burger';
const burgerJoints = restaurants.filter(isBurger);
/// -----------
const isCuisine = comparison => ({cuisine}) => cuisine === comparison;
var isCuisineX = function isCuisine(comparison) {
return function (_ref) {
var cuisine = _ref.cuisine;
return cuisine === comparison
}
}
isCusine("asdf")
restaurants.filter(isBurgerX)
// -----------------
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
showTasks: function() {
this.tasks.forEach(function(task) {
console.log(this.name + " wants to " + task); // this === window (function = global scope)
}/*.bind(this)*/);
}
};
var bunny = {
name: 'Usagi',
tasks: ['transform', 'eat cake', 'blow kisses'],
showTasks() {
this.tasks.forEach((task) => { // => references the surrounding scope
console.log(this.name + " wants to " + task);
});
}
};
bunny.showTasks();
// async
async function getUsers(users) {
try {
response[0] = await axios.get(`/users/userId=${users[0]}`);
response[1] = await axios.get(`/users/userId=${users[1]}`);
response[2] = await axios.get(`/users/userId=${users[2]}`);
response[3] = await axios.get(`/users/userId=${users[3]}`);
} catch (err) {
console.log(err);
}
}
async function getTop10() {
const response = await fetch("url...");
const json = await respon.json();
console.log(json);
}
// map - iterate through array and send each value as an arg via func(val)
// fetch in JS ES6
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
// for (let income of incomes) ...
// rest operator (check spread operator)
let test = (...args) => console.log('args: ', args[3]);
test(1,2,3,4)
["a","b","c"].includes("a") // true
// import export
// file:modules.js
export const data = [1,2,3];
// file:index.js
import { data } from './modules.js'
// ------------helpers--------------------
_has = function(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
var lazy = [].slice.call(document.querySelectorAll(".test"));
lazy.forEach(item =>item.classList.add("visible"));
// CLASS
export class Test {
constructor(param) {
this.param = param;
}
static test() { return 1010; }
get prop() { return `getter ${this.param}`; }
}
import Test from '....'
let test = new Test("asdf");
// generators
var myGen = function*() {
var one = yield "foo";
var two = yield "bar";
console.log('log:', one, two); // 2, a
}
var gen = myGen();
console.log(gen.next());
console.log(gen.next(2));
console.log(gen.next("a"));
console.log(gen.next("b"));
Promise.coroutine(function* () {
var data = yield {
tweets: $.get('tweets.json'),
profile: $.get(...)
};
console.log(data.tweets, ...)
})();
// ---------------------------------- reduce + filter
json.reduce((accumulator, item) => {accumulator[item.gender] => item}, {male:[], female: []});
json = [{i:1}, {i:2}, {i:3}, {i:4}]
Array.prototype.filter = function(fn) {
return this.reduce((items, item, index) => {
if(fn(item))
items.push(item);
return items;
}, []);
}
arr = json.filter(item => item.i >= 2);
console.log(arr);
Array.prototype.forEach = function(fn) {
this.reduce((acc, item, index) => {
item = fn(item, index)
},[]);
};
arr.forEach( (item, index) { do something } );
json.map(item => item.DB_ID);
// ---------------- pew pew filter
// https://css-tricks.com/level-up-your-filter-game/
const isKeyEqualToValueX = key => value => object => object[key] === value;
var isKeyEqualToValue = function isKeyEqualToValue(key) {
return function (secondCallValue) {
return function (filterItem) {
return filterItem[key] === secondCallValue
}
}
}
const isCuisine = isKeyEqualToValue('cuisine');
const isBurger = isCuisine('Burger');
const burgers = restaurants.filter(isBurger)
// --------------------- promises
let cleanRoom = function () {
return new Promise((resolve, reject) {
resolve('this will be returned as an argument in .then');
}
}
cleanRoom().then(result => {
return anotherPromise(result);
});
Promise.all([all promises to run]).then(() => console.log('all done'));
// Promise.race -> first finished returns