Igor Suvorov
Программист-предприниматель
5 Nov 2016
typeof 123 // "number"
typeof true // "boolean"
typeof "foo" // "string"
typeof {id:12, name: "John"} // "object"
typeof [1, 4, 9] // "object"
typeof null // "object" (1)
typeof undefined // "undefined"
typeof function(){ return 1+1; } // "function" (2)
P.S. Lodash; _.isArray(ar)
var re = /ab*c/ig;
var re = new RegExp('ab*c', 'ig');
// ac
// Abc
// aBBBBBBBc
var str = "HelloaBBBBBBBcWorld Hacker";
str.replace(re, ' JS ');
// Hello JS World H JS ker
var date = new Date();
// Wed Feb 17 2016 16:01:50 GMT+0400 (SAMT)
var str = "Wed Feb 17 2016 16:01:50 GMT+0400 (SAMT)"
var date = new Date(str);
var str = date.toISOString();
// 2016-02-17T12:01:50.000Z
var timestamp = date.getTime(); 1455710510000
timestamp = 1*date;
timestamp = +date;
P.S. Moment.js
var user = {
firstName: "John",
lastName: "Connor",
age: 8 * 2
};
var json = JSON.stringify(user);
// {firstName:"John",lastName: "Connor",age:16}
/**
* Как-то отправляем в браузер, и как-то принимаем
*/
var user = JSON.parse(json);
if(user.age < 18){
alert("Вход запрещен");
}
// Синхронно
var rounded = Math.round(1.5);
// do something else
/////////
// Асинхронно
var data = null;
getData({userId:123}, function(raw){
data = Math.round(raw);
// do something else
})
// чтото паралельное
function getData(server, userId, /*...*/ next){
// do something
}
//////////
getData("https://vk.com", 1,
function(err, user, html /*...*/){
})
while(new Date().getTime() < now + 1000) {
// ничего не делаем
}
console.log("Прошла одна секунда, друг")
/// Запрос к базе
/// Запрос на диск
/// Запрос в гугл
setTimeout(function(){
console.log("Прошла одна секунда, друг")
/// Запрос к базе
/// Запрос на диск
/// Запрос в гугл
}, 1000);
setTimeout(function(){
console.log("Прошла одна секунда, друг")
requestToDB({ userId:101001 }, function(err, user){
if (err) {
return showError(err);
} else {
findInFile("apple.json", function(err, userJson){
if(err){
return showError(err);
}
findInGoogle("Steve Jobs", function(err, data){
if(err){
return showError(err);
}
showSuccess(user,userJson,data)
});
});
}
});
}, 1000);
function isUserTooYoung(id, callback) {
openDatabase(function(err, db) {
if (err) showError(err);
getCollection(db, 'users', function(err, col) {
if (err) showError(err);
find(col, {'id': id},function(err, result) {
if (err) showError(err);
result.filter(function(err, user) {
if (err) showError(err);
callback(user.age < cutoffAge)
})
})
})
})
}
function isUserTooYoung(id) {
return openDatabase(db)
.then(getCollection)
.then(find.bind(null, {'id': id}))
.then(function(user) {
return user.age < cutoffAge;
})
.catch(showError)
}
function isUserTooYoung(id) {
return openDatabase(db)
.then(getCollection)
.then(find.bind(null, {'id': id}))
.then(function(user) {
return user.age < cutoffAge;
})
.carch(showError)
}
async function isUserTooYoung(id) {
try {
const a = await openDatabase(db)
const b = await getCollection(a)
const user = await find(b, {'id': id})
return user.age < cutoffAge;
} catch (err) {
showError(err)
}
}
class ColorPoint extends Point {
static getSquare(point1, point2) {
return Math.abs(point1.x - point2.x) *
Math.abs(point1.y - point2.y);
}
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toObject() {
return {
...super.toObject(),
color: this.color,
};
}
}
const point1 = new Colorpoint(30, 40, 'red')
const point2 = new Colorpoint(10, 20, 'red')
console.log(ColorPoint.getSquare(point1, point2))
// Expression bodies
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var pairs = evens.map(v => ({even: v, odd: v + 1}));
// Statement bodies
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
// Lexical this
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
}
// Basic literal string creation
`In JavaScript '\n' is a line-feed.`
// Multiline strings
`In JavaScript this is
not legal.`
// String interpolation
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// Construct an HTTP request prefix is used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
Content-Type: application/json
X-Credentials: ${credentials}
{ "foo": ${foo},
"bar": ${bar}}`(myOnReadyStateChangeHandler);
function f() {
{
let x;
{
// okay, block scoped name
const x = "sneaky";
// error, const
x = "foo";
}
// error, already declared in block
let x = "inner";
}
}
function f(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) == 15
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
npm i babel-cli -g
babel-node index.js
babel-node tools/run start
| node ./src/utils/bunyan -o short -l trace
node start.js
{
"scripts": {
"babel-build": "rimraf lib &&
babel src --out-dir lib --source-maps inline --copy-files &&
cp {package.json,README.md} lib/"
}
}
.babelrc
{
"presets": [
"es2015",
"react",
"node5",
"stage-0"
],
"plugins": [
"jsx-control-statements",
"react-require",
"transform-decorators-legacy"
]
}
{
"dependencies": {
"babel-preset-es2015": "^6.9.0",
"babel-preset-node5": "^11.1.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
}
}
npm init
npm install
npm install --save lodash express svg2png
npm start
npm run dev
{
"name": "svg",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"start": "node index.js",
"prod": "npm install && node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "isuvorov",
"license": "ISC",
"dependencies": {
"lodash": "^3.10.1",
"express": "^4.13.4",
"svg2png": "^3.0.0"
}
}
npm i -S express
npm i -g nodemon
npm i -D bunyan
статьте лайки, подписывайтесь на канал
telegram.me/isuvorov
vk.com/igor.suvorov
github.com/isuvorov
By Igor Suvorov
"summary" : "#!md * Основные архитектурные особенности JavaScript. * Новым конструкциям ES6, ES7. * JavaScript на сервере - Node.js. * Пакетный менеджер NPM. * Инструментом Babel. * Паттерны асинхронного программирования (Promises, Async-await).