Skip to content

Instantly share code, notes, and snippets.

@tsvetkovpro
Last active December 24, 2020 19:32
Show Gist options
  • Save tsvetkovpro/639b0f1edd626936054b to your computer and use it in GitHub Desktop.
Save tsvetkovpro/639b0f1edd626936054b to your computer and use it in GitHub Desktop.
js:
// 1
var arr = [];
var filesArr = ['file.jpg', 'secfile.jpg', 'elsefile.jpg'];
filesArr.forEach(function(element) {
var obj = {};
obj['image_id'] = element;
arr.push(obj);
});
document.getElementById('res').innerHTML = JSON.stringify(arr);
<div id="res"></div> // [{"image_id":"file.jpg"},{"image_id":"secfile.jpg"},{"image_id":"elsefile.jpg"}]
//2
window.onload = function() {
var arr = [];
var filesArr = ['file.jpg', 'secfile.jpg', 'elsefile.jpg'];
arr = filesArr.map(function(el) {
return {
image_id: el
};
});
document.getElementById('res').innerHTML = JSON.stringify(arr);
}
<div id="res"></div> // [{"image_id":"file.jpg"},{"image_id":"secfile.jpg"},{"image_id":"elsefile.jpg"}]
// Add a Class
// To add a class, we’ll write a function that takes in the elements we want to change and adds a specified class to all of them.
function addClass(elements, myClass) {
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have only one dom element, make it an array to simplify behavior
else if (!elements.length) { elements=[elements]; }
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
if (!(' '+elements[i].className+' ').indexOf(' '+myClass+' ') > -1) {
elements[i].className += ' ' + myClass;
}
}
}
// You’ll see how the function works soon, but to watch the function in action, feel free to use this CSS:
.red{
background: red;
}
.highlight{
background: gold;
}
// …and this HTML:
<div id="iddiv" class="highlight">ID div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
<div class="classdiv">Class div</div>
addClass('#iddiv','highlight');
addClass('.classdiv','highlight');
addClass(document.getElementById('iddiv'),'highlight');
addClass(document.querySelector('.classdiv'),'highlight');
addClass(document.querySelectorAll('.classdiv'),'highlight');
// Remove a Class
// To remove a class, we can use the following function:
function removeClass(elements, myClass){
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
// if we have only one dom element, make it an array to simplify behavior
else if (!elements.length) { elements=[elements]; }
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
}
// Modifying Classes the Modern Way
// Browsers from IE10 and up support a property called classList, which makes an element’s classes much easier to deal with.
/*
The following properties are available:
length — the number of class names applied
item(index) — the class name at a specific index
contains(class) — returns true if a node has that class applied
add(class) — applies a new class to the node
remove(class) — removes a class from the node
toggle(class) — removes or adds a class if it’s applied or not applied respectively
We can use this in preference to the clunkier className property:
*/
document.getElementById("myelement").classList.add("myclass");
// Add Class
function addClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// add class to all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.add(myClass);
}
}
// usage examples:
addClass('.class-selector', 'example-class');
addClass('#id-selector', 'example-class');
// Remove Class
function removeClass(selector, myClass) {
// get all elements that match our selector
elements = document.querySelectorAll(selector);
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].classList.remove(myClass);
}
}
// usage examples:
removeClass('.class-selector', 'example-class');
removeClass('#id-selector', 'example-class');
// We’ve covered how to add and remove classes through className (the compatible way) and classList (the more modern way).
// Метод Element.classList.toggle добавляет класс, если он отсутствует у элемента, иначе — убирает. Когда вторым параметром передано false — удаляет указанный класс, а если true — добавляет.
// 1. Array literal
let numbers = [1, 5, 7, 8];
let planets = ['Earth', 'Mercury', 'Jupiter'];
let mixed = [1, 'Earth', null, NaN, undefined, ['Mars']];
// First case: usual array literal
let items = ['first', 'second', 'third'];
items; // => ['first', 'second', 'third']
// Second case: a noop comma at the end
let items = ['first', 'second', 'third', ];
items; // => ['first', 'second', 'third']
//Third case: no element between commas
let items = [, 'first', 'second', 'third'];
items; // => [<1 empty slot>, 'first', 'second', 'third']
items[0]; // => undefined
items[1]; // => 'first'
items.length; // => 4
// When the array literal has commas with no element between, a sparse array is created too:
let items = ['first', , 'second', 'third'];
items; // => ['first', <1 empty slot> ,'second', 'third']
items[0]; // => 'first'
items[1]; // => undefined
items.length; // => 4
// 1.2 Improved by spread operator
let source = ['second', 'third'];
let items = ['first', ...source];
items; // => ['first', 'second', 'third']
let odds = [1, 3, 5];
let evens = [4, 6];
let zero = 0;
let negative = -1;
let items = [...odds, zero, ...evens, negative];
items; // => [1, 3, 5, 0, 4, 6, -1]
// Let's create a generator function that accepts first argument as the elements value and the second argument as the number of elements. Then use it with spread operator and array literal to instantiate a new array:
function* elements(element, length) {
let index = 0;
while (length > index++) {
yield element;
}
}
[...elements(0, 5)]; // => [0, 0, 0, 0, 0]
[...elements('hi', 2)]; // => ['hi', 'hi']
//2. Array constructor
// From constructor invocation
let arrayConstr = new Array(1, 5);
arrayConstr; // => [1, 5]
typeof arrayConstr; // => 'object'
arrayConstr.constructor === Array; // => true
// From array literal
let arrayLiteral = [1, 5];
arrayLiteral; // => [1, 5]
typeof arrayLiteral; // => 'object'
arrayLiteral.constructor === Array; // => true
// 2.1 Numeric argument creates sparse array
let items = new Array(3);
items; // => [<3 empty slots>]
items.length; // => 3
// 2.2 Enumerating elements
let items = new Array('first', 'second', 'third');
items; // => ['first', 'second', 'third']
let source = new Array('second', 'third');
let items = new Array('first', ...source);
items; // => ['first', 'second', 'third']
// 2.3 Useful static methods
let zeros = new Array(5).fill(0);
zeros; // => [0, 0, 0, 0, 0]
let zeros = Array.from(new Array(5), () => 0);
zeros; // => [0, 0, 0, 0, 0]
let items = Array.from(new Array(5), (item, index) => index + 1);
items; // => [1, 2, 3, 4, 5]
// Let's use a generator object (which is an iterable) to create a list of incremented numbers (like the example above):
function* generate(max) {
let count = 0;
while (max > count++) {
yield count;
}
}
let items = Array.from(generate(5));
items; // => [1, 2, 3, 4, 5]
let itemsSpread = [...generate(5)];
itemsSpread; // => [1, 2, 3, 4, 5]
// When an array should be initialized with calculated on each iteration elements, Array.from() is a nice solution.
// If an array should be loaded with the same value, use Array.prototype.fill() in combination with new Array(length).
// Do not underestimate the power of iterable objects and generator functions, which can be combined with the spread operator in an array literal or used directly in Array.from() static method.
// INSERT the number 2 between the 1 and 3
var my_array = [0,1,3,4];
var start_index = 1;
var number_of_elements_to_remove = 0;
my_array.splice(start_index, number_of_elements_to_remove, 2);
console.log(my_array);
//[1,2,3,4];
var my_array = ["a","b","c","k","d"];
var start_index = 3
var number_of_elements_to_remove = 1;
var removed_elements = my_array.splice(start_index, number_of_elements_to_remove);
console.log(removed_elements);
//["k"]
console.log(my_array);
//["a","b","c","d"];
// example of REMOVING an element from an array in javascript.
var my_array = ["a","b","c","k","d"];
var start_index = 3
var number_of_elements_to_remove = 1;
var removed_elements = my_array.splice(start_index, number_of_elements_to_remove);
console.log(removed_elements);
//["k"]
console.log(my_array);
//["a","b","c","d"];
// REPLACING some elements in a javascript array with the splice() method
var my_array = ["baseball", "basketball", "tennis", "golf"];
var start_index = 1
var number_of_elements_to_remove = 2;
var removed_elements = my_array.splice(start_index, number_of_elements_to_remove, "boxing", "bowling", "volleyball");
console.log(removed_elements);
//["tennis", "golf"]
console.log(my_array);
//["baseball", "boxing", "bowling", "volleyball", "golf"];
// Забудьте уже DOM Event Level 0 Inline! Т.е. вставку обработчиков в HTML - onclick='бла-бла-бла'
let data = {
id: {
SELECT: '#money',
INPUT: '#cash',
PRICE: '#price',
SIGN: '#sign'
},
value: {
rub: "руб",
usd: '$'
}
};
document.addEventListener('DOMContentLoaded', e => { // Ждём загрузки DOM, чтобы найти элементы
let select = document.querySelector(data.id.SELECT),
input = document.querySelector(data.id.INPUT);
select.addEventListener('change', signHandler);
input.addEventListener('keyup', priceHandler);
signHandler.call(select); // Сразу выберем знак
priceHandler.call(input); // И значение
});
function signHandler(){
document.querySelector(data.id.SIGN).textContent = data.value[this.selectedOptions[0].value];
}
function priceHandler(){
let price = this.value === '' ? '0' : this.value;
document.querySelector(data.id.PRICE).textContent = price;
}
<select id="money">
<option value="rub">Russia</option>
<option value="usd">USA</option>
</select>
<input id="cash" value='0'><br />
<span><span id='price'></span> <span id='sign'></span</span>
var str = "Вот такая строка";
function deleteFirstStmbol ( string ) {
return string.slice(0,2);
}
console.log(deleteFirstStmbol(str));
// Functional Concepts For JavaScript Developers: Currying
/*
“The concept is simple: You can call a function with fewer arguments than it expects.
It returns a function that takes the remaining arguments.”
*/
var add = function(x, y) {
return x + y;
}
add(10, 20); // 30
// Here we have a function that takes two numbers and returns the sum. Simple. Let’s curry it.
var add = function(x) {
return function(y) {
return x + y;
}
}
var addFifty = add(50);
addFifty(10); // 60
// Let’s assume we’re working with a list of animals like the below:
const animals = [
{
id: 1,
name: "Tails",
type: "Cat",
adoptable: false
},
{
id: 2,
name: "Soul",
type: "Cat",
adoptable: true
},
{
id: 3,
name: "Fred",
type: "Dog",
adoptable: true
},
{
id: 4,
name: "Fury",
type: "Lion",
adoptable: true
}
];
// We need a way to filter down these animals based on type. We could do something like this:
animals.filter(animal =>
animal.type === "Cat"
);
/*
[{
adoptable: false,
id: 1,
name: "Tails",
type: "Cat"
},
{
adoptable: true,
id: 2,
name: "Soul",
type: "Cat"
}];
*/
// Let’s see if we can do better.
const isAnimal =
type =>
animal =>
animal.type === type
animals.filter(isAnimal("Cat"));
/*
[{
adoptable: false,
id: 1,
name: "Tails",
type: "Cat"
},
{
adoptable: true,
id: 2,
name: "Soul",
type: "Cat"
}];
*/
// http://www.barbarianmeetscoding.com/blog/2016/06/14/functional-programming-in-javascript/
// получение название трека с сайта http://tidido.com/ru/u17592186065408/playlists/565756fc3fa4df654c8b4567
/*
структура
<div class="song-info song-play ">
<div class="song-title">
<a title="Last Sun" href="/ru/a35184372136399/al560130e0e7c622686a854ff7/t560130e1e7c622686a8550d4"> Last Sun </a>
</div>
<div class="song-artist">
<a href="/ru/a35184372136399" title="Fjordne">Fjordne</a>
</div>
</div>
*/
список всех песен
list = document.getElementsByClassName('song-info song-play ')
list[1].childNodes[3].childNodes[1].title // назвние группы
list[1].childNodes[1].childNodes[1].title // название песни
for(var i=0; i<list.length; i++) {
console.log(list[i].childNodes[1].childNodes[1].title + ' - ' + list[i].childNodes[3].childNodes[1].title)
};
// получение элемента по классу и изменение его свойства
window.onload = function(){
var p = document.getElementById('blinking');
p.style.fontWeight = 'bold';
setInterval(function(){
if (p.style.fontWeight == 'normal') {
p.style.fontWeight = 'bold';
} else {
p.style.fontWeight = 'normal';
}
}, 1000);
}
// get links on page
var l = document.links;
for(var i in r){console.log(r[i].text)}
for(var i in r){(r[i].style['color']='green')}
// В новых браузерах можно использовать forEach для NodeList, например, выводит ссылки на все изображения в консоль.
document.querySelectorAll('img').forEach(img => console.log(img.src))
$(document).ready(function() {
$(".sh-list li").click(function() {
var $this=$(this);
if ($this.hasClass('active')) return;
$(".sh-list li.active, .sh-cont.active").add(`[data-item="${$this.data('item')}"]`)
.toggleClass('active');
//localStorage["selected"] = $this.data('item');
});
/*
if (localStorage["selected"]) {
$(`[data-item="${localStorage["selected"]}"]`).addClass('active');
}
*/
});
.sh-list li {
cursor: pointer;
}
.sh-list li.active {
color: red;
}
.sh-cont {
display: none;
}
.sh-cont.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="sh-list">
<li data-item="b1" class="b1 active">Block 1</li>
<li data-item="b2" class="b2">Block 2</li>
<li data-item="b3" class="b3">Block 3</li>
</ul>
<div data-item="b1" class="sh-cont b1 active">text 1</div>
<div data-item="b2" class="sh-cont b2">text 2</div>
<div data-item="b3" class="sh-cont b3">text 3</div>
/*
В простом случае, если у элементов списка будет только один класс, можно по нему и определять выбранный, а также сохранять этот класс в localStorage и использовать его при загрузке
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var my_array = ['a', 'b', 'c'];
for (var i=0; i<my_array.length; i++) {
console.log(my_array[i]); //a b c
}
my_array.forEach(function(current_value) {
console.log(current_value); //a b c
});
console.log("\n");
var array_of_numbers = [5, 7, 1, 9, 8, 5];
array_of_numbers.forEach(function(current_value, index, initial_array) {
if (current_value % 2) {
console.log('odd');
}
else {
console.log('even');
}
}); //odd, odd, odd, odd, even, odd
console.log("\n");
var even_numbers = [];
var odd_numbers = [];
function separate_evens_from_odds(value) {
if ( value % 2 ) {
odd_numbers.push(value);
}
else {
even_numbers.push(value);
}
}
var array_of_numbers = [5, 7, 1, 9, 8, 5];
array_of_numbers.forEach(separate_evens_from_odds);
console.log(even_numbers); //[8]
console.log(odd_numbers); //[5, 7, 1, 9, 5]
console.log("\n");
var total_cost = 0;
function add_to_total_cost(amount) {
total_cost += amount.cost;
}
var shopping_cart_1 = [
{
item: 'shirt',
cost: 22
},
{
item: 'shorts',
cost: 26
}
];
var shopping_cart_2 = [
{
item: 'cereal',
cost: 4
},
{
item: 'milk',
cost: 3
},
{
item: 'eggs',
cost: 2
}
]
shopping_cart_1.forEach(add_to_total_cost);
shopping_cart_2.forEach(add_to_total_cost);
console.log(total_cost); //57
</script>
</head>
<body>
</body>
</html>
// Object Literals
var o = {
x: 42,
y: 3.14,
f: function() {},
g: function() {}
};
// Factory Functions
function thing() {
return {
x: 42,
y: 3.14,
f: function() {},
g: function() {}
};
}
var o = thing();
// Prototype Chains
var thingPrototype = {
f: function() {},
g: function() {}
};
function thing() {
var o = Object.create(thingPrototype);
o.x = 42;
o.y = 3.14;
return o;
}
var o = thing();
// Instead, a prototype object is created for us automatically alongside every function, and we can put our shared data there.
thing.prototype.f = function() {};
thing.prototype.g = function() {};
function thing() {
var o = Object.create(thing.prototype);
o.x = 42;
o.y = 3.14;
return o;
}
var o = thing();
// ES5 Classes
function create(fn) {
var o = Object.create(fn.prototype);
fn.call(o);
return o;
}
// ...
Thing.prototype.f = function() {};
Thing.prototype.g = function() {};
function Thing() {
this.x = 42;
this.y = 3.14;
}
var o = create(Thing);
//The “create” function we defined is actually a rudimentary version of the “new” keyword, and we can drop-in replace “create” with “new”.
Thing.prototype.f = function() {};
Thing.prototype.g = function() {};
function Thing() {
this.x = 42;
this.y = 3.14;
}
var o = new Thing();
// ES6 Classes
class Thing {
constructor() {
this.x = 42;
this.y = 3.14;
}
f() {}
g() {}
}
var o = new Thing();
function Excuse() {
var myDog = ['dog', 'cat', 'sense of ennui', 'hamster', 'chinchilla', 'iguana', 'turtle', 'best friend', 'bro', 'boo', 'crush', 'sister', 'brother', 'nemesis', 'doppelganger', 'gerbil', 'bunny', 'fish', 'crew'];
var ate = ['ate', 'peer-reviewed', 'destroyed', 'deleted', 'erased', 'remixed', 'twitched', 'recycled', 'livetweeted', 'undermined', 'underbid', 'upcycled', 'gave away', 'plagiarised', 'confiscated', 'barfed on', 'stole', 'ransomed', 'spilled water on', 'lost', 'misplaced', 'buried', 'shredded', 'hid', 'liberated', 'left with', 'ebayed', 'craigslisted', 'etsyed', 'tweeted', 'instagrammed', 'snapchatted', 'youtubed', 'dunked on', 'subteweeted', 'favorited', 'upvoted', 'downvoted', 'live cast', 'pinned', 'vlogged', 'blogged about'];
var myHomework = ['homework', 'project', 'essay', 'film project', 'visualization', 'infographic', 'pre-writing', 'term paper', 'lab report', 'reading log', 'summary', 'article', 'flash cards', 'study guide', 'textbook', 'workbook', 'reading book', 'diorama', 'poster', 'dreams', 'laptop', 'computer', 'tablet', 'momentum', 'report', 'slideshow', 'slide deck', 'presentation', 'worksheet', 'handout', 'notes', 'portfolio', 'blog post', 'comment'];
var who = myDog[Math.round(Math.random()*(myDog.length-1))];
var did = ate[Math.round(Math.random()*(ate.length-1))];
var what = myHomework[Math.round(Math.random()*(myHomework.length-1))];
document.getElementById('excuses').innerHTML = '<div>My ' + who + ' ' + did + '<br> my ' + what + '.</div>'
}
// Remove the first character
var myString = '!thisIsMyString';
var sillyString = myString.substr(1);
// Remove the last character
var myString = 'thisIsMyString!';
var sillyString = myString.slice(0, -1);
// Remove the first character and last character
var myString = '!thisIsMyString!';
var sillyString = myString.substr(1).slice(0, -1);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
#current-recall-img img {
width: 100%;
}
.recall img {
width: 200px;
}
</style>
</head>
<body>
<main>
<div class="recall">
<img alt="" class="img" src="http://bart.com.ua/wp-content/uploads/2015/03/gradina-1333657576.jpg" />
<div class="comment">Комментарий</div>
<div class="date">25.05.16</div>
<div class="master">Ирина</div>
<div class="salon">Таганка</div>
</div>
<div class="recall">
<img alt="" class="img" src="http://zonahelp.ru/wp-content/uploads/2013/05/44.jpg" />
<div class="comment">Комментарий</div>
<div class="date">25.05.16</div>
<div class="master">Ирина</div>
<div class="salon">Таганка</div>
</div>
<div class="recall">
<img alt="" class="img" src="http://bart.com.ua/wp-content/uploads/2015/03/gradina-1333657576.jpg" />
<div class="comment">Комментарий</div>
<div class="date">25.05.16</div>
<div class="master">Ирина</div>
<div class="salon">Таганка</div>
</div>
<div id="preview" style="position: absolute; right: 0;top:0; width: 400px; height: 400px;border: 1px solid red; display: none;">
<img id="current-recall-img" />
</div>
</main>
<script>
var imageList = document.querySelectorAll('.recall > img');
var i = imageList.length;
while (i--) {
imageList[i].addEventListener('click', showimg);
}
function showimg(e) {
var imgSrc = null;
if (e.target.tagName == 'IMG') {
imgSrc = e.target.src
}
var preview = document.getElementById('preview');
var currentImage = document.getElementById('current-recall-img');
preview.style.display = 'block';
currentImage.src = imgSrc;
};
</script>
</body>
</html>
// Shuffling An Array
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var flintstones = ["Pebbles", "Bam-Bam", "Wilma", "Fred"];
shuffle(flintstones); // > ["Wilma", "Bam-Bam", "Fred", "Pebbles"]
// You can use the sort method to sort an array:
flintstones.sort(); //["Bam-Bam", "Fred", "Pebbles", "Wilma"]
//However, things get tricky if we try to sort numerical information:
var ranValues = [ 7, 11, 12, 15, 3, 1, 10 ];
//Sorting the array yields this rather confusing result: [1, 10, 11, 12, 15, 3, 7]
// What’s going on? By default, sort works in lexicographical order: i.e. a dictionary sort.
// Fortunately, we can pass a function into the sort method to control the sorting process. To sort numerals correctly use:
sort(function(a,b){return a - b})
// This function takes two values from the array, a and b. It will only return one of three values: -1 means that a is less than b, and should be placed before it; 0 means that the values are equal, and no change should be applied, and 1 means that a should be placed after b. Applied to our array example produces the correct, expected result:
ranValues.sort(function(a,b){return a - b}); //> [1, 3, 7, 10, 11, 12, 15]
ranValues.sort(function(a,b){return b - a}); //> [15, 12, 11, 10, 7, 3, 1]
// На собеседовании задали вопрос: "Как отсортировать массив, не используя метод .sort(), посредством ES6
let a = [3, 2, 1, 1, 5, 4],
c = [];
for (; a.length;) { c.push(a.splice(a.indexOf(Math.min(...a)),1)[0])}
console.log(c)
//
let arr = [5, 3, 6, 4, 4, 7];
console.log('input: ' + arr);
let arrCopy = arr.slice(0, arr.length);
let result = [];
arrCopy.map(() => {
let minElementIndex = 0;
minElementIndex = arr.indexOf(Math.min.apply(Math, arr));
result.push(arr[minElementIndex]);
arr.splice(minElementIndex, 1);
});
console.log('output: ' + result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment