var duration = 32 * 60 * 1000;
var step = 1000;
var endsAfter = duration;
var timer = setTimeout(alert, duration, 'Hello world!');
var interval = setInterval(function() {
endsAfter -= step;
if (endsAfter <= 0) clearInterval(interval);
console.log('Timeout через: ', endsAfter);
}, step);
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
[
<li key="1">1</li>,
<li key="2">2</li>,
<li key="3">3</li>,
<li key="4">4</li>,
<li key="5">5</li>,
]
<ul>
{listItems}
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
const initialState: {
entities: {}.
isLoading: {
'ALL': false,
},
isError: {
'ALL': false,
}
}
const someEntityReduser = (state = initalState, action) => {
const { type, payload } = action;
switch (type) {
case GET_ALL_ENTITIES_REQUEST:
return {
...state,
isLoading: {
...state.isLoading,
'ALL': true,
},
isError: {
...state.isError,
'ALL': false,
},
};
case GET_ALL_ENTITIES_SUCCESS:
return {
...state,
entities: payload, // либо нормализация если приходят массивом
isLoading: {
...state.isLoading,
'ALL': false,
},
};
case UPDATE_ENTITY_REQUEST:
return {
...state,
isLoading: {
...state.isLoading,
[payload.id]: true,
},
isError: {
...state.isError,
[payload.id]: false,
},
};
case UPDATE_ENTITY_SUCCESS:
return {
...state,
entities: {
...state.entities,
[payload.id]: payload,
},
isLoading: {
...state.isLoading,
[payload.id]: false,
},
};
/* other cases */
}
}
function SetUserManager(config) {
this.client = new ClientUser();
this.clientManager = new ClientManager({
user: this.client
});
this.options = {
name: config.name,
key: config.key
};
this.cookies = [];
client.login(options);
this.viewer();
}
SetUserMagager.prototype.viewer = function() {
this.client.on('login', () => {
this.client.setLogin();
});
this.client.on('msg', (session) => {
serveSession(session);
});
this.clientManager.on('user', (data) => {
serveNewUser(data);
});
}
class SetUserMagager {
constructor(config) {
this.client = new ClientUser();
this.clientManager = new ClientManager({
user: this.client
});
this.options = {
name: config.name,
key: config.key
};
this.cookies = [];
client.login(options);
this.viewer();
}
viewer() {
this.client.on('login', () => {
this.client.setLogin();
});
this.client.on('msg', (session) => {
serveSession(session);
});
this.clientManager.on('user', (data) => {
serveNewUser(data);
});
}
}
module.exports.person = async () => await sqlQuery();
module.exports.person = async () => [await sqlQuery1(), await sqlQuery2()];
module.exports.person = async id => {
const user = await getUser(id);
const permissions = await getPermissions(user.role);
return {
user,
permissions,
};
}
module.exports.person = args => sqlQuery(args);
const user = async person(id);
class Counter {
constructor(value) {
this.value = value || 0; // определяем поле класса value со значением аргумента value
} // либо 0 если аргумент не будет передан
getVaue() {
return this.value;
}
increment() {
return ++this.value;
}
decrement() {
return --this.value;
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
Array.prototype.forEach.call(arguments, data => this.add(data));
}
add(data) {
const nodeToAdd = new Node(data);
let nodeToCheck = this.head;
if(!nodeToCheck) {
this.head = nodeToAdd;
this.length++;
return nodeToAdd;
}
while(nodeToCheck.next) {
nodeToCheck = nodeToCheck.next;
}
nodeToCheck.next = nodeToAdd;
this.length++;
return nodeToAdd;
}
get(num) {
const nodeToCheck = this.head;
let count = 0;
if(num > this.length) {
return "Doesn't Exist!"
}
while(count < num) {
nodeToCheck = nodeToCheck.next;
count++;
}
return nodeToCheck;
}
remove(num) {
let nodeToCheck = this.head;
let length = this.length;
let count = 0;
let prevNode = null;
if(num > length) {
return "Doesn't Exist!"
}
if(num === 0) {
this.head = nodeToCheck.next;
this.length--;
return this.head;
}
while(count < num) {
prevNode = nodeToCheck;
nodeToCheck = nodeToCheck.next;
count++;
}
prevNode.next = nodeToCheck.next;
nodeToCheck = null;
this.length--;
return this.head;
}
}
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
const isVisited = localStorage.getItem("isVisited");
if (!isVisited) {
localStorage.setItem("isVisited", true);
}
class Home extends Component {
...
render() {
if (!isVisited) return <Redirect to="/nobel-laureates" />
...
}
}
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
var t0 = performance.now();
var t1;
doSomething().then(result => {
t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
});
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(() => {
setTimeout(() => console.log('1000'), 1000);
sleep(5000).then(() => {
console.log('5');
});
})();
Cannot assign to read only property
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
func.apply(window);
this.setState({ ... }, () => this.getStateValues());
handleChange = ev => {
const { name, value } = ev.target;
const symbols = split('')(value);
const result = filter(i => characterVerification(i), symbols);
this.setState({
[name]: join('')(result)
}, () => this.getStateValues(),
);
};
constructor(props) {
super(props);
this.state = props.params;
this.onFieldChange = this.onFieldChange.bind(this); // тут
}
renderSingleValue(data = {}) {
...
let self = this; // бессмысленно
return (
<input type="text"
...
onChange={self.onFieldChange}
...
/>
);
}
constructor() {
const self = this;
node.addEventListener('click', function() {
self.handleEvent(); // сработает, так как функция вызывается на self
});
}
constructor() {
const self = this;
node.addEventListener('click', self.handleEvent); // не сработает, функция передается
// в колбек обработчика события
} // и не будет вызываться на self
class Example extends Component {
state = {
inputValue: '',
};
handleChange = e => { // arrow class field function биндится на контекст экземпляра
const { name, value } = e.target;
this.setState({
[name]: value,
});
};
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
}
class Example extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const { name, value } = e.target;
this.setState({
[name]: value,
});
}
render() {
const { inputValue } = this.state;
return (
<Wrapper>
<input
name="inputValue"
value={inputValue}
onChange={this.handleChange}
/>
...
</Wrapper>
);
}
}
handleChange = value => {
const { name, onChange } = this.props;
const fakeEvent = { target: { name, value } };
onChange(fakeEvent);
};
state = { ...prevState, ...newState };
this.setState(prevState => ({
some_data: {
...prevState.some_data,
...input,
},
});