Git Product home page Git Product logo

blog's People

Contributors

cityray avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

blog's Issues

[JS] Moment.js some examples

Use Moment.js UTC to Local time

  • Put UTC time into moment.js
let utcTime = moment.utc('2016-12-21T15:31:57.847').format('YYYY-MM-DD HH:mm:ss');
  • Conver to local timezone
let localTime  = moment.utc('2016-12-21T15:31:57.847').toDate()
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');

取得星期幾

moment.utc('2017-01-12T15:31:57.847').format('d');

加減

  • today
moment().format('YYYY-MM-DD');
  • 加1
moment.utc('2017-01-12T15:31:57.847').add(1, 'days').format('d');
  • 減1
moment.utc('2017-01-12T15:31:57.847').subtract(2, 'days').format('d');

Start of Time

  • 本月第一天
moment.utc('2017-01-12T15:31:57.847').startOf('month').format('YYYY-MM-DD');
  • 本週第一天
moment.utc('2017-01-06T15:31:57.847').startOf('week').format('YYYY-MM-DD');
  • 本季第一天
moment.utc('2017-01-06T15:31:57.847').startOf('quarter').format('YYYY-MM-DD');

[JS] Regular Expression

Regular Expression (正規表達式)

  • 移除 <script> tag 及內容
    text.replace(/<(script).*?>[\s\S]*?<\/\1>/ig, 'dangerous');

[JS] RxJS 點點紀錄

[gulp] Gulp 使用紀錄

Install

確認是否安裝過 Gulp

$ npm -g ls --depth=0

Npm Global Install Gulp

$ npm install -g gulp

Usage

Create gulpfile.js

gulp.task('mytask', function () {
    console.log('執行 default 的任務');
});

執行 gulp

$ gulp mytask

plugin

.pipe(header('\ufeff'))
  • gulp-replace
    可運用 regex replace,取代檔案中的指定文字
.pipe(replace(/ReplaceByGulp/ig, 'new text'))
// bundle.config.js
module.exports = {
  bundle: {
    main: {
      scripts: [
        './content/js/foo.js',
        './content/js/baz.js'
      ],
      styles: './content/**/*.css'
    },
    vendor: {
      scripts: './bower_components/angular/angular.js'
    }
  },
  copy: './content/**/*.{png,svg}'
};

gulp.js 中加入

gulp.task('bundle', function() {
  return gulp.src('./bundle.config.js')
    .pipe(bundle())
    .pipe(gulp.dest('./public'));
});

Reference

[JS] Javascript stack / event loop / callback queue / async

[VS] MSBuild Command-Line

利用 MSBuild Command,進行專案發佈,可存成 (*.bat) 進行發佈

Exmaple

"C:\Program Files (x86)\MSBuild\14.0\Bin\Msbuild" "C:\yourproject\project.csproj" /p:DeployOnBuild=true /p:PublishProfile=project.pubxml

@ping 127.0.0.1 -n 3 -w 1000 > nul

"C:\Program Files (x86)\MSBuild\14.0\Bin\Msbuild" "C:\yourproject\project2.csproj" /p:DeployOnBuild=true /p:PublishProfile=project2.pubxml

PAUSE

MSBuild Command-Line Reference

[JS] Manipulating(iterate) objects with Object.keys()

Object.keys()

將 Object 中的 Key 轉換成 Array,然後再運用 Array (forEach, map) 進行 loop.

Sample 1

// Sample 1
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj));

for (let key of Object.keys(obj)) {  
  let objName = obj[key];
  // ... do something with obj
  console.log(objName);
}

Sample 2

// Sample 2
var nameObj = {first: "Zaphod", last: "Beeblebrox"};
Object.keys(nameObj).forEach(function(key) {
    console.log(key + ': ' + nameObj[key]);
});

Sample 3

// Sample 3
var countries = {
    China: 1371980000,
    India: 1276860000,
    'United States': 321786000,
    Indonesia: 255461700,
    Brazil: 204873000,
    Pakistan: 190860000
};
var countriesFiltered = Object.keys(countries).filter(function(key) {
    return countries[key] <= 1000000000;
}).map(function(key) {
    return countries[key];
});
console.log(countriesFiltered);

refer

[HTML 5] Resources

[JS] JS Development Environment

Development Webservers

  • Express
  • budo
  • Browsersync
  • Webpack dev server
  • http-server
  • live-server

share work-in-progress

npm Scripts

npm config set init-author-name [yourname]
npm config set init-author-email [[email protected]]
npm config set init-author-url [http://your.url]
npm config set init-license MIT

Bundlers

// webpack example
import path from 'path';

export default {
    debug: true,
    devtool: 'inline-source-map',
    noInfo: false,
    entry: [
        path.resolve(__dirname, 'src/index')
    ],
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    plugins: [],
    module: {
        loaders: [
            { test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] },
            { test: /\.css$/, loaders: ['style', 'css'] }
        ]
    }
}

Linter - ESlint

// .eslintrc.json
{
    "root": true,
    "extends": [
        "eslint:recommended",
        "plugin:import/errors",
        "plugin:import/warnings"
    ],
    "parserOptions": {
        "ecmaVersion": 7,
        "sourceType": "module"
    },
    "env": {
        "browser": true,
        "node": true,
        "mocha": true
    },
    "rules": {
        "no-console": 1
    }
}

// command
# eslint --fix xxx.js
# eslint --print-config xxx.js

Disable Eslint

/* eslint-disable semi, xxx, xxx */
or
/* eslint semi: 0 */

Disable Eslint line

// eslint-disable-line semi, no-undef

Testing

Frameworks

Assertion

Run without browser

End-to-End testing

Continuous Integration

  • Travis
  • Jenkins
  • AppVeyor

Http Calls

Mocking

Polyfill

Error Logging(Tracking)

Cloud Hosting

  • AWS
  • Azure
  • Heroku
  • GCP
  • Firebase
  • Github Page (Static files only)

Git

Deploy

Find Start Project

[JS] Javascript 加載監控數據 - PerformanceTiming

獲取頁面加載監控數據 PerformanceTiming

DNS解析時間: domainLookupEnd - domainLookupStart
TCP建立連接時間: connectEnd - connectStart
白屏時間: responseStart - navigationStart
dom渲染完成時間: domContentLoadedEventEnd - navigationStart
頁面onload時間: loadEventEnd - navigationStart

Sample Code

# sample 1
let startTag = 'start-func';
let endTag = 'end-func';
window.performance.mark(startTag);
# your code
window.performance.mark(endTag);
window.performance.measure(`test func mark init`, startTag, endTag);

# sample 2
window.performance.mark('RemoveMessage');
let start = performance.now();
# your code
let end = performance.now();
console.log('Spend:' + (end - start) + 'ms');

Reference

[JS] Intro ES6

ES6 compatibility table(相容性表格)

TC39 - ECMAScript

Syntax

Modules and Classes

  • Module & Named Export
  • Class, extends, super
  • Properties for Class Instances
  • Static Members
  • new.target

New Types

Object Extensions (res)

  • Object.assign
  • Object.setPrototypeOf
  • Object.defineProperty
  • Object.is

Iterable, Iterator

How to Learn

Blog

[JS] [].forEach.call(NodeList) hack & Array.map

querySelectorAll 預設 return non array
可透過[]去訪問陣列的屬性 .forEach
取代 Array.prototype.forEach.call(...) 的簡易寫法

[].forEach

    var divs = document.querySelectorAll('div');

    [].forEach.call(divs, function(div) {
        console.log(div);
    });

more refer to Ditch the [].forEach.call(NodeList) hack


Other scenario, 建立空的長度為10的Array,並跑迴圈10次

Array.map

    [...Array(10)].map((d, i) => {
        // do somethgin ....
        return i;
    });

[F2E] 監控網頁FPS

透過 requestAnimationFrame API 來查看瀏覽器的每秒 FPS

var lastTime = performance.now();
var frame = 0;
var lastFameTime = performance.now();
var loop = function(time) {
    var now =  performance.now();
    var fs = (now - lastFameTime);
    lastFameTime = now;
    var fps = Math.round(1000/fs);
    frame++;
    if (now > 1000 + lastTime) {
        var fps = Math.round( ( frame * 1000 ) / ( now - lastTime ) );
        frame = 0;    
        lastTime = now;    
    };           
    window.requestAnimationFrame(loop);   
}

Refer

[JS] createDocumentFragment improve DOM performance

createDocumentFragment

console.time("createDocumentFragment initialize");
var body = document.body;  
var fragment = document.createDocumentFragment();  
for(var i = 0; i< 100000; i++) {  
    var text1 = document.createElement('span');
    text1.innerHTML = 'hello world';
    fragment.appendChild(text1);
}
body.appendChild(fragment);  
console.timeEnd("createDocumentFragment initialize");

createElement

console.time("appendChild initialize");
var body = document.body;  
var element = document.createElement('div');  
for(var i = 0; i< 100000; i++) {  
    var text = document.createElement('span');
    text.innerHTML = 'hello world';
    element.appendChild(text);
}
body.appendChild(element);  
console.timeEnd("appendChild initialize");

Babel

Understanding Babel

- Let us to use next generation Javascript by Compiling it to ES5

Installing

Installing node.js

node.js OR NVM

 

Check NPM Global Packages Location

# npm ls -g --depth 0

 

Installing Babel

# npm install -g babel-cli

 

Check Babel Version

# babel --version

 

Setting Project

Creates package.json

# npm init

 

Transpiling ES5 with Babel

Installing via plugins

# npm install babel-preset-es2015 --save-dev

Create src/app.js file

let name = "Ray";
console.log(`Hello ${name} !`);

Transpiling app.js to build directory

# babel src --presets es2015 -d build

Or Bundle each files into one bundle js

# babel src --presets es2015 --out-file build/bundle.js

Add "-s" flag, which is for source maps

# babel src --presets es2015 --out-file build/bundle.js -s

Or Watch source files, add -w flag

# babel src --presets es2015 --out-file build/bundle.js -s -w

 

If you create .babelrc file and setting it first

{
    "presets" : ["es2015"],
    "sourceMaps" : true
}

babel command line will be short

# babel src --out-file build/bundle.js -w

 

reference

[JS] Object.assign 合併物件

Object.assign 合併為一個新的物件,並建立新的 array

Method 1 (rest parameter)

    // ES6
    let state = {
        todos: [{
            id: 0,
            completed: false,
            text: 'Initial todo for demo purposes'
        }]
    }

    let newObj = Object.assign({}, state, {
        //建立一個新array,不會影響到原本的array
        todos: [{
            id: 1,
            text: "new text",
            completed: false
        }, ...state.todos]
    })

    console.log(newObj)
    console.log(state)

Method 2 (array concat)

    let newObj = Object.assign({}, state)

    //建立一個新array,不會影響到原本的array
    newObj.todos = state.todos.concat({
                    id: 1,
                    text: "new text",
                    completed: false
                })

    console.log(newObj)
    console.log(state)

Method 3 (array filter)

    let state = {
        todos: [{
            id: 0,
            completed: false,
            text: 'Initial todo for demo purposes'
        },
        {
            id: 1,
            completed: false,
            text: 'New Text2'
        }]
    }

    let newObj = Object.assign({}, state)

    //建立一個新array,不會影響到原本的array
    newObj.todos = state.todos.filter((val) => val.id >= 0)
    newObj.todos.push({id:3, text: 'new text3', completed: true})

    console.log(newObj)
    console.log(state)

refer

[JS] JavaScript 禁止 Browser 特定快捷鍵

禁用滑鼠右鍵

    $('body').on('contextmenu', function() {
        return false;
    });

禁用快速鍵

$('body').on('keydown',function(e) {
        e = window.event || e;

        // 禁止 F5
        if(e.keyCode == 116){
            try {
                e.keyCode = 0; //IE 需設 keyCode 為 false
            } catch(err) {
                console.log(err);
            }

            return false;
        }

        // 禁止 Alt+ 方向键 ←
        // 禁止 Alt+ 方向键 →
        if ((e.altKey) && ((e.keyCode == 37) || (e.keyCode == 39)))
        {
            e.returnValue = false;
            return false;
        }

        // 禁止 Backspace
        if(e.keyCode == 8){
            return false;
        }

        // 禁止 ctrl+R
        if((e.ctrlKey) && (e.keyCode == 82)){
            try {
                e.keyCode = 0; //IE 需設 keyCode 為 false
            } catch(err) {
                console.log(err);
            }

            return false;
        }
    });

[JS] Curry Function in Javascript

curry.js

module.exports = function curry(fn) {
    return function curried(...args) {
        if(args.length >= fn.length) {
            return fn(...args);
        } else {
            return function(a) {
                return curried(...[...args, a]);
            }
        }
    }
};

app.js

var curry = require('./curry');

function add(a, b) {
    return a + b;
}

var curryAdd = curry(add);

var add10 = curryAdd(10);

console.log(add10(5));
console.log(add10(10));

console.log(curryAdd(10, 8));

執行 node (v6.2.2)

node app.js

refer

[待...] FrontEnd Develop Tools

git Config Setting (初始值設定)

git config --global user.name " [yourname]"
git config --global user.email "[[email protected]]"

git config --global color.diff auto
git config --global color.status auto
git config --global color.branch auto
git config --global color.log auto 

Git - Git 與 Github 版本控制超簡易教學

npm Config Setting (初始值設定)

Config Setting

npm config set init-author-name "[yourname]"
npm config set init-author-email "[[email protected]]"
npm config set init-author-url "[http://your.url]"
npm config set init-license "MIT"

#紀錄確切版本
npm set save-exact true

Config Preview

npm config ls -l

npm基本命令介绍
npm模块管理器

npm-run-all, rimraf

https://npmcdn.com/

semantic-release

babel webpack

mocha chai

nyc (istanbul) coveralls

travis-ci

http://shields.io/

eslint

ESLint 使用入門

nodemon

使用 nodemon 執行 node 程式,檔案編修後 nodemon 會自動重新執行 node 程式

npm install -g nodemon

[JS] React Performance 優化方法紀錄

[npm] npm-check - update npm package

npm-check

If you have the list of dependencies and dev-dependencies for your application( update your package.json).

To see what needs to be upgraded, we can use a super-handly Node.js module called npm-check.


Requirements

Node >= 0.11.

Install

$ npm install -g npm-check

Use

$ npm-check

Options

  • You can refer to offical document. npm-check

[JS] Javascript 演算法整理

[jQuery] jQuery Snippets

Back to Top Button

$('a.top').on('click', function(){
	$(document.body).animate({scrollTop : 0},800);
	return false;
});

// or
$("a[href='#top']").on('click', function() {
	$("html, body").animate({ scrollTop: 0 }, "slow");
	return false;
});

Nav Stay on top

$(function(){
	var $win = $(window)
	var $nav = $('.mytoolbar');
	var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top;
	var isFixed=0;

	processScroll()
	$win.on('scroll', processScroll)

	function processScroll() {
	var i, scrollTop = $win.scrollTop()

	if (scrollTop >= navTop && !isFixed) { 
		isFixed = 1
		$nav.addClass('subnav-fixed')
	} else if (scrollTop <= navTop && isFixed) {
		isFixed = 0
			$nav.removeClass('subnav-fixed')
	}
}

Enabling/Disabling Input Fields

$('input[type="submit"]').attr("disabled", true);
$(‘input[type="submit"]').removeAttr("disabled”);

Zebra Striping

$('li:odd').css('background', ‘#e7e7e7’);

Prevent Link Functionality

$(“a.disable").on("click", function(e){
  e.preventDefault();
});

Toggle Classes

$(“.main”).toggleClass(“selected”);

Automatically fix broken images

$('img').error(function(){
	$(this).attr('src', 'img/broken.png');
});

Detect Copy, Paste and Cut Behavior

$("#textA").bind('copy', function() {
    $('span').text('copy behaviour detected!')
}); 
$("#textA").bind('paste', function() {
    $('span').text('paste behaviour detected!')
}); 
$("#textA").bind('cut', function() {
    $('span').text('cut behaviour detected!')
});

Tabs Switch

$('.tab_nav li:first').addClass('active').show();
$('.content').hide();
$('.content:first').show();

$('.tab_nav li').on('click', function(){

    $('.tab_nav li').removeClass('active');

    $(this).addClass('active');
    $(".content").hide();

    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(1000); //Fade in the active ID content
    return false;

});


<!-- TAB SECTION  -->
<div id="tabs">
    <ul class="tab_nav">
        <li><a href="#tab1">tab 1</a></li>
        <li><a href="#tab2">tab 2</a></li>
    </ul>
    <div class="tab_content">
        <div id="tab1" class="content"></div>
        <div id="tab2" class="content"></div>
    </div>
</div>

[Node] fs-extra - fs extra module

Method

  • ensureDir (確認資料夾是否存在,否則建立資料夾)
  • copy,可利用 filter 過濾不被複製的檔案

Usage

const fs = require('fs-extra');

const filterLibFunc = (src, dest) => {
	const regex = /node_modules|.babelrc|bundle.config.js/i;
	if (src.match(regex )) return false;
	return true;
};

fs.ensureDir(DIR)
	.then(() => {
	  console.log('EnsureDir Success!');

	  fs.copy(fromDir, toDir, { filter: filterLibFunc })
	    .then(() => console.log('Copy Files Success!'))
	    .catch(err => console.error(err));
	})
	.catch(err => {
	  console.error(err)
	});

Reference

[Node] 支援跨平台 NODE_ENV

1. Installation

npm install --save-dev cross-env

2. Usage

{
  "scripts": {
    "prod": "cross-env Version=1.0.1.1 node prod.js"
  }
}

3. Get Value

在 prod.js 中就能抓取到 'Version' 值

console.log(process.env.Version);

Reference

[JS] JS Concept Article

[DEV] Git

Git Commands

  • git status -s (Show changes since commit)
  • git add . (State chnaged files)
  • git commit -m "Firest Commit" (Commit staged files wigth message)
  • git reset HEAD^ (Undo last commit and keep changes)

Git Hook

  • Pre-commit
    • Spellcheck
    • Run tests
  • Post-commit
  • Pre-push

Install

  • pre-commit is a pre-commit hook installer for git

[JS] throttle & debounce

throttle 與 debounce,可運用在 resize, keyin or mousemove 等情境


Debounce

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

use

var searchInputFunc = debounce(function () {                    
    var _val = $(this).val().trim();
    console.log(_val);

    // dosomething...

}, 500);

Throttle

function throttle(func, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,
      deferTimer;
  return function () {
    var context = scope || this;

    var now = +new Date,
        args = arguments;
    if (last && now < last + threshhold) {
      // hold on to it
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        func.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      func.apply(context, args);
    }
  };
}

use

$('body').on('mousemove', throttle(function (event) {
  console.log('tick');
  // dosomething...

}, 1000));

or can use lodash debounce
防抖和节流原理分析
7分钟理解JS的节流、防抖及使用场景

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.