July 25, 2018 | In: Programovanie

JS in 2018 – list of all the things I read

npm install node-sass sass-loader style-loader --save-dev
npm install bulma --save // css framework
npm run dev
npm install axions --save // a simple http lib

// jsonplaceholder.typicode.com (# dummy data like comments...)

npm install -g @angular/cli
ng // (| ng -v)
ng new compare-angular --routing style=sass
cd... && ng serve

ng generate component home // (|| ng g c home)

// webpack -> handles frontend modules (require is not valid (build from node.js) and replaces to a valid browser js)

npm install webpack-dev-server --save-dev
// https://codequs.com/p/r1p4sHM5z/continuous-development-without-hitting-ctrl-r-with-webpack-4

Transpiling code means converting the code in one language to code in another similar language. (sass -> css, TS ->JS)

import syntax isn’t much different from the require syntax, but import has extra flexibility for more advanced cases

setup js workflow: https://codequs.com/p/SyIn0WvzQ/modern-javascript-explained-for-dinosaurs

webpack-bundle-analyzer: https://youtu.be/ivQ7HrnBJe8?t=920

hoisting: takes declaration+functions not value to the top
scope: var a = 1; func a = 2 => looks if the a vas defined, if not, looks up
context === this (window === this)
obj.foo.call(window) => zmeni context this v obj na window
#div.slideToggle(300, fnc() {...}.bind(this)); -> outside scope

if(false) { var example = 5 }; console.log(example); // error -> hoisting

arrow functions: let x = num => x * 2;

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

observable -> stream of data / definition / wrapper for some functionality
observer -> executes a code when new value is recieved -> subscribes to observable

observable [-----[next()]-----[next()]----...]
				 observer	  observer 
				 
react:
storybook
gatsby js (static js generator based on graphql)
nextjs

// -----------------------------------------------
// NG ----------------------------------------------
// -----------------------------------------------

attributes - HTML -> used to init DOM, cannot change
properties - DOM -> angular:  myId is defined in the NG component class | used for NOT string values
	 directives with template ->  -> will be rendered with custom html/css
directive ->  -> structural dom change

// 2 way binding (bannana in a box) [()]
...
...

...html...
...html...

https://youtu.be/RhemSul_Up0?t=5225
component 
@Input() public propNameFromParent -> recieving data from parent (|| @Input("propNameFromParent") public myName
@Output() public childEvent = new EventEmitter(); -> child sending to parent -> as we dont have parent elemnt component we send events
>> this.childEvent.emit("some data")...

...

// ovservables
- an observable is a sequence of items that arrive async over time (an HTTP response)

// https://youtu.be/RhemSul_Up0?t=8781 (+catch)
service: getMethod(): Observable{ 
	return this.http.get(("...url...");
}

// routing: https://youtu.be/RhemSul_Up0?t=9339
https://youtu.be/RhemSul_Up0?t=11783 (relativeRouting)

// read GET param: https://youtu.be/RhemSul_Up0?t=10573 (ActivatedRoute)
this.route.snapshot.paramMap.get('id')

// progressive web app PWA
https://itnext.io/turning-an-angular-6-app-into-a-progressive-web-app-9e6fc6361ba6
https://medium.com/progressive-web-apps/a-new-angular-service-worker-creating-automatic-progressive-web-apps-part-1-theory-37d7d7647cc7
https://medium.com/google-developer-experts/a-new-angular-service-worker-creating-automatic-progressive-web-apps-part-2-practice-3221471269a1
google PWA checklist


// Lighthouse 
lighthouse http://localhost:8080 --view (runs the test and spits out a report)

headless chrome 
calibre tool


stencil ionic web component -> performance
capacitor
cross device build: 
https://medium.com/@Amit_Shukla/deploy-angular-6-0-html-js-css-app-to-mobile-web-and-desktop-using-ionic-capacitor-106e84d66a96

test:
test:

Building an Ionic Geolocation Tracker with Google Map and Track Drawing


https://github.com/syedmoosakaleem95/Ionic-3—Google-Maps-API
https://capacitor.ionicframework.com/docs/apis/haptics

Ionic Local Notifications (Schedule, Payload and Callback) [v3]

Share This:

Comments are closed.