pro js points

ashkan nasirzadeh اشکان نصیرزاده

اشکان نصیرزاده

۱- استفاده از ; در نسخه های جدید جاوااسکریپت اختیاری است.
۲- اولین بلاک ، نگاه به اسکوپی هست که توش هست بعد به همین ترتیب میره بلاک ها را بالاتر
۳- برای یافتن استرینگی در استرینگ دیگر که TRUE یا FALSE به جای INDEX_OF از includes استفاده کن
۴- حذف فضا های خالی در استرینگ با مند trim()
۵- فقط جایی از let‍ استفاده می کنیم که مطمئن هستیم می خواهیم اون رو تغییر بدیم و اگر نه cons خیلی پرفورمنس بالا تری داره
۶- اگر آبجکتی رو به صورت const تعریف کنیم ولی مقادیر و پراپرتی هاشو می تونیم همچنان تغییر بدیم
۷- متد unshift به اول آرایه اضافه می کنه و بعکسش shift هست که از اول آرایه کم می کنه
۸- متد push به آخر آرایه اضافه می کنه و برعکسش pop از اخر آرایه کم می کنه
۹- document یعنی به DOM اشاره دارد
۱۰- در سرچ ها از ایونت input استفاده کنید نه keyup
۱۱ - جاوااسکریپت از مرورگر تاریخش را می خواند. (let a = new Date)
۱۲ - برای تاریخ جلالی از کتابخونه moment استفاده کن (*۵۷*)
۱۳ - وقتی که از this استفاده می کنیم دیگر نباید از arrow function ها استفاده کنیم

function message () {
    console.log('hello world');
}
----------------------------------------------------
let message = function () {
    console.log('hello world');
}
----------------------------------------------------
let message = () => {
    console.log('hello world');
}
// search in an array of objects
let items = [
    {
        title: 'book1',
        name: 'ali',
        price: '300'
    },
    {
        title: 'book2',
        name: 'hosein',
        price: '200'
    },
    {
        title: 'book3',
        name: 'ashkan',
        price: 200
    }
]
function findItem () {
    let item = items.findIndex((v, i) => {
        return v.title == 'book3'
    })
    return items[item];
}
console.log(findItem());
// search in array of objects 
let items = [
    {
        title: 'book1',
        name: 'ali',
        price: '300'
    },
    {
        title: 'book2',
        name: 'hosein',
        price: '200'
    },
    {
        title: 'book3',
        name: 'ashkan',
        price: 200
    }
]
function findItem () {
    return items.find((v, i) => {
        return v.title == 'book3'
    })
}
console.log(findItem());
// delete member indexed n of an array:
array.splice(n, 1);
let items = [
    {
        title: 'book1',
        name: 'ali',
        price: '300'
    },
    {
        title: 'book2',
        name: 'hosein',
        price: '200'
    },
    {
        title: 'book3',
        name: 'ashkan',
        price: 200
    }
]
let price200s = items.filter(item => {
    return item.price == 200;
})
console.log(price200s);

// output:
// [
//   { title: 'book2', name: 'hosein', price: '200' },
//   { title: 'book3', name: 'ashkan', price: 200 }
// ]
let items = [
    {
        title: 'book1',
        name: 'ali',
        price: 300
    },
    {
        title: 'book2',
        name: 'hosein',
        price: 200
    },
    {
        title: 'book3',
        name: 'ashkan',
        price: 200
    }
]
let items2 = items.sort(function (a, b) {
    if (a.price > b.price) return -1;
    else return 1;
})
console.log(items2);

//output:
// [
//   { title: 'book1', name: 'ali', price: 300 },
//   { title: 'book2', name: 'hosein', price: 200 },
//   { title: 'book3', name: 'ashkan', price: 200 }
// ]
// hint:
// return -1 => put a before b
// return 1 => put a after b
// get a tag (first of all):
let p = document.querySelector('p')
// get all tags of a kind:
let ps = document.querySelectorAll('p')
//get an id:
document.querySelector('#id')
//get some classes:
document.querySelectorAll('.class')
// remove a tag:
p.remove()
// get textContent of a tag:
p.textContent
// get an element from a form:
document.querySelector('#form').addEventListener('submit', (e) => {
        e.preventDefault()
        return e.target.elements.formElementName.value
})
localStorage.setItem('product', 'ashi')

let product = localStorage.getItem('product')
console.log(product)

localStorage.removeItem('product')

localStorage.clear()

// reload page by changing storge key example:
window.addEventListener('storage', (e) => {
    if (e.key === 'example') {}
})
// change the location of page:
location.assign('http://www.google.com')
two codes below are equal:
----------------------------------------------------
const func1 = (item) => {
    return item
}
----------------------------------------------------
const func1 = item => item
// make a constructor
const User = function (email) {
    this.username = email
}
User.prototype.func1 = function (message) {
    this.message = message
}

const username1 = new User('ali')
username1.func1('test')
console.log(username1)
// User { username: 'ali', message: 'test' }
// make a constructor with class
class User {
    constructor(email) {
        this.email = email
    }
    func1(message) {
        this.message = message
    }
}
const username1 = new User('ali')
username1.func1('test')
console.log(username1);
// User { email: 'ali', message: 'test' }
// subclasses :
class User {
    constructor(email) {
        this.email = email
    }
    func1(message) {
        this.message = message
    }
}
class Job extends User {
    constructor (email, job) {
        super(email)
        this.job = job;
    }
}
const username1 = new Job('ali', 'baghkar')
console.log(username1);
// setters and getters
// get for return something from object in object.getterFunc mode not object.getterFunc()
// set for seting something of object in mode of object.setterFunc = something
const products = {
    name: 'book1',
    price: '399',
    set new(stringed) {
        const stringedParts = stringed.split(' ')
        this.name = stringedParts[0]
        this.price = stringedParts[1]
    },
    get info() {
        let stringed = this.name + this.price
        return stringed
    }
}
products.new = 'book2 56'
console.log(products.info);
// setters and getters in class
class product {
    constructor(name) {
        this.name = name
    }
    set addPrice(price) {
        this.price = price
    }
    get info() {
        return `hello world ${this.name}, ${this.price}`
    }
}
const product1 = new product('ghablame')
product1.addPrice = '2000'
console.log(product1.info);
// callback functions
const aFuncWithCallback = (callback) => {
    setTimeout(() => {
        console.log('func1')
        callback()
    }, 2000);
}
const callbackFunc = () => {
    console.log('callbackFunc')
}
aFuncWithCallback(callbackFunc)
// output:
// func1
// callbackFunc
// Promises
const aFuncWithPromise = () => {
    return new Promise ((resolve, reject) => {
        console.log('func1')
        const error = false;
        if (!error) {
            resolve()
        } else {
            reject('Error has been occured')
        }
    })
}
const callbackFunc = () => {
    console.log('callbackFunc')
}
aFuncWithPromise().then(callbackFunc)
// output:
// func1
// callbackFunc
// Promises and async await
const aFuncWithPromise = () => {
    return new Promise ((resolve, reject) => {
        setTimeout(() => {
            console.log('func1')
            const error = false;
            if (!error) {
                resolve()
            } else {
                reject('Error has been occured')
            }
        }, 3000);
    })
}
const callbackFunc = () => {
    setTimeout(() => {
        console.log('callbackFunc')
    }, 2000);
}
async function todo () {
    await aFuncWithPromise();
    callbackFunc();
}
todo();
// output:
// func1
// callbackFunc
// app.js AJAX with javascript and promises get data from api
const getbtn = document.querySelector('#getbtn')
const postbtn = document.querySelector('#postbtn')

const sendHttpRequest = (method, url) => {
    const promise = new Promise ((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open(method, url)
        xhr.responseType = 'json'
        xhr.onload = () => {
            resolve(xhr.response)
        }
        xhr.onerror = () => {
            reject('Error')
        }
        xhr.send()
    })
    return promise
}

const getData = () => {
    sendHttpRequest('GET', 'https://jsonplaceholder.typicode.com/posts/1')
        .then(response => {
            console.log(response)
        })
        .catch(e => {
            console.log(e)
        })
}
const postData = () => {

}

getbtn.addEventListener('click', getData)
postbtn.addEventListener('click', postData)
// app.js AJAX with javascript and promises post data to api added
const getbtn = document.querySelector('#getbtn')
const postbtn = document.querySelector('#postbtn')

const sendHttpRequest = (method, url, data) => {
    const promise = new Promise ((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open(method, url)
        xhr.responseType = 'json'
        if (data) {
            xhr.setRequestHeader('Content-Type', 'application/json')
        }
        xhr.onload = () => {
            resolve(xhr.response)
        }
        xhr.onerror = () => {
            reject('Error')
        }
        xhr.send(JSON.stringify(data))
    })
    return promise
}

const getData = () => {
    sendHttpRequest('GET', 'https://jsonplaceholder.typicode.com/posts/1')
        .then(response => {
            console.log(response)
        })
        .catch(e => {
            console.log(e)
        })
}
const postData = () => {
    sendHttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts', {
        userId: 2,
        id: 2,
        title: 'Post Title',
        body: 'post body kia'
    }).then(res => {
        console.log(res)
    }).catch(e => {
        console.log(e)
    })
}

getbtn.addEventListener('click', getData)
postbtn.addEventListener('click', postData)

// app.js Ajax api with fetch - GET data
const getbtn = document.querySelector('#getbtn')
const postbtn = document.querySelector('#postbtn')

const sendhttpRequest = (method, url, data) => {
    return fetch(url)
        .then(res => {
            return res.json()
        })
}

const getData = () => {
    sendhttpRequest('GET', 'https://jsonplaceholder.typicode.com/posts/1')
        .then(res => {
            console.log(res)
        })
}
const postData = () => {

}

getbtn.addEventListener('click', getData)
postbtn.addEventListener('click', postData)

// app.js Ajax api with fetch - post data
const getbtn = document.querySelector('#getbtn')
const postbtn = document.querySelector('#postbtn')

const sendhttpRequest = (method, url, data) => {
    return fetch(url, {
        method: method,
        body: JSON.stringify(data),
        headers: data ? { 'Content-Type': 'application/json'} : {}
    })
        .then(res => {
            return res.json()
        })
}

const getData = () => {
    sendhttpRequest('GET', 'https://jsonplaceholder.typicode.com/posts/1')
        .then(res => {
            console.log(res)
        })
}
const postData = () => {
    sendhttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts', {
        userId: 2,
        id: 2,
        title: 'ali',
        body: 'Post body ashi'
    }).then(res => {
        console.log(res)
    })
}

getbtn.addEventListener('click', getData)
postbtn.addEventListener('click', postData)

// app.js Ajax api with axios
const getbtn = document.querySelector('#getbtn')
const postbtn = document.querySelector('#postbtn')

const getData = () => {
    axios.get('https://jsonplaceholder.typicode.com/posts/1')
        .then(res => {
            console.log(res)
        })
}
// for send to php
// var data = new FormData();
// data.append('title', 'foo');
// data.append('body', 'bar');

axios.post('api/post.php', data)
const postData = () => {
    axios.post('https://jsonplaceholder.typicode.com/posts', {
        userId: 2,
        id: 2,
        title: 'ali',
        body: 'gholi'
    })
        .then(res => {
            console.log(res)
        })
}

getbtn.addEventListener('click', getData)
postbtn.addEventListener('click', postData)

// rest in javascript
const myFunc = (...price) => {
    let sum = 0
    price.forEach(item => sum += item)
    console.log(sum)
}
myFunc(1,2)
// output: 3
myFunc(3,2,3)
// output: 8
// rest in javascript
const myFunc = (...books) => {
    console.log(books.join(', '))
}
myFunc('math', 'physics')
// output: math, physics
myFunc('bookYek', 'bookDo', 'bookSe')
// output: bookYek, bookDo, bookSe
// spreads in javascript
let array = ['book1', 'book2', 'book3']
let products = [...array, 'book4']
console.log(products)
// output:
// [ 'book1', 'book2', 'book3', 'book4' ]
// destructing in javascript
let obj = {
    name: 'kia',
    age: '24'
}
const { name, age, exists = true } = obj
console.log(name)
console.log(age)
console.log(exists)

// output:
// kia
// 24
// true
// destructing in javascript
let arr = ['kia', 'soophie']
const [ male, female, exists = true ] = arr
console.log(male)
console.log(female)
console.log(exists)

// output:
// kia
// soophie
// true
npm install babel-cli -g

babel --version
npm install babel-preset-env
babel modern.js -o old.js --presets env
OR
babel moders.js -o old.js --presets env --watch
npm install webpack webpack-cli

{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "webpack": "webpack --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11"
  }
}

const path = require('path')
module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'public')
    }
}
// util.js
console.log('this is util.js')

// index.js
import './util'
console.log('this is index.js')
// util.js
export const func1 = item => console.log(item)

// index.js
import { func1 } from './util'
func1('gholi')
// util.js
const tellProduct = product => console.log(product)
export default tellProduct

// index.js
import tp from './util'
tp('book')
// util.js
const func1 = item => console.log(item)
const tellProduct = product => console.log(product)
export {func1, tellProduct as default}

// index.js
import tp, {func1} from './util'
tp('book')
func1('ali')
// upload pic for api
function uploadPic () {
    let file = document.getElementById('imggg').files[0]
    let form = new FormData()
    form.append('file', file)
    form.append('kask', 'khaniKiaAmir@!')
    form.append('action', 'uploadIMG')
    $.ajax({
        url: 'http://sapi.sazekomak.com/settings.php',
        data: form,
        processData: false,
        contentType: false,
        method: 'post'
    })
    .done(function (a) {
        console.log(a)
    })
    .fail(function () {
        alert('fail')
    })
}