Skip to content

Instantly share code, notes, and snippets.

View SergeyLipko's full-sized avatar

SergeyLipko

  • Kharkiv, Ukraine
View GitHub Profile
@SergeyLipko
SergeyLipko / custom_filter.js
Last active April 19, 2017 10:44
Handmade Array.prototype.filter()
const _arr = [
{ name: 'Mark', age: 21 },
{ name: 'Dan', age: 22 },
{ name: 'Zoe', age: 29 },
{ name: 'Victor', age: 21 },
{ name: 'Martin', age: 21 }
];
const filtered = _arr.filter(i => i.age === 21 );
@SergeyLipko
SergeyLipko / promises.js
Last active April 19, 2017 10:54
All about promises
/*
* Сильные стороны
* 1) Композиция промисов (chaining)
* 2) API - методы типа all и race
*/
// * * * * * Default composition * * * * *
// всегда использовать return внутри then или выдавать ошибку при помощи throw
function promiseAxios() {
axios.get("http://localhost:8080/api/user")
@SergeyLipko
SergeyLipko / obj_asignment.js
Last active April 18, 2017 20:27
Передача объектов по ссылке
// в переменную "a" копируется ссылка на объект "b"
var a = b = {
value: 1,
};
var b = {
value: 2,
};
// следовательно когда изменяются какие-то поля объекта в переменной "a"
@SergeyLipko
SergeyLipko / async_await.js
Last active April 21, 2017 12:50
All about async await functions
/*
Основная идея async await - избавиться от коллбеков, которые использую промисы, интуитивно понятный механизм
отлова ошибок через try catch ну и последовательная обработка, представляющая собой "синхронное" представление
*/
function baz() {
return new Promise((res) => {
setTimeout(() => {
res('hey baz')
}, 500)
@SergeyLipko
SergeyLipko / custom_map.js
Last active May 3, 2017 18:23
Handmade Array.prototype.map()
function customMap(arr, callback, thisArgs) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(callback.call(thisArgs, arr[i]));
}
return newArr;
}
@SergeyLipko
SergeyLipko / map_forEach_difference.js
Created April 19, 2017 10:54
How Array.prototype.map() and Array.prototype.forEach() works
const myArr = [1, 2, 3, 4, 5, 6];
// map создает новый массив на основании вызова callback для каждого элемента (трансформация)
const newMap = myArr.map(i => {
return i * 2;
});
// forEach выполняет callback для каждого элемента массива (перебор)
const newForEach = myArr.forEach(i => {
return i * 2;
@SergeyLipko
SergeyLipko / tasks.js
Last active March 2, 2023 17:27
Задачки
// TODO - подумать, каким образом выполнить все это в функциональном стиле
// * * * * * Заполнение массива * * * * *
// Заполнить массив нулями и единицами, при этом данные значения
// чередуются, начиная с нуля.
function foo2() {
const len = 10;
let arr = [];
const reslut = someFunc(); // запись результат выполнения someFunc в переменную result
const funcLink = somfFunc; // запись ссылки на функцию в переменную funcLink
// * * * * * Default example * * * * *
this.age = 20;
const module = {
age: 12,
showAge: function() {
/*
To learn this, you first have to learn what this is not, despite any assumptions or misconceptions that
may lead you down those paths. this is neither a reference to the function itself, nor is it a reference
to the function's lexical scope.
this is actually a binding that is made when a function is invoked, and what it references is determined
entirely by the call-site where the function is called.
*/
// ля получения значений подобно циклу for...of, можно использовать метод
let arr = [ 3, 5, 7 ];
arr.foo = "hello";
arr.forEach(function (element, index) {
console.log(element); // выведет "3", "5", "7"
console.log(index); // выведет "0", "1", "2"
});