cityray / blog Goto Github PK
View Code? Open in Web Editor NEWPersonal Blog
Personal Blog
let utcTime = moment.utc('2016-12-21T15:31:57.847').format('YYYY-MM-DD HH:mm:ss');
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');
moment().format('YYYY-MM-DD');
moment.utc('2017-01-12T15:31:57.847').add(1, 'days').format('d');
moment.utc('2017-01-12T15:31:57.847').subtract(2, 'days').format('d');
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');
function toType (obj) {
if (typeof obj === 'undefined') {
return 'undefined';
}
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
text.replace(/<(script).*?>[\s\S]*?<\/\1>/ig, 'dangerous');
Learn RxJS (GitBook)
egghead.io RxJS Lessons
RxJS Observables Crash Course - youtube
用例子讲解 RxJS 5 的 Operators
RxJS 中文教學文件 - 匯智網
RxJS 教程 "Reactive Programming是神马?"
希望是最淺顯易懂的 RxJS 教學
将RxJS融入React项目
RxJS by Example: Part 1
RxJS by Example: Part 2
RxJS by Example: Part 3
RxJS by Example: Part 4
確認是否安裝過 Gulp
$ npm -g ls --depth=0
Npm Global Install Gulp
$ npm install -g gulp
gulp.task('mytask', function () {
console.log('執行 default 的任務');
});
$ gulp mytask
.pipe(header('\ufeff'))
.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'));
});
利用 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
將 Object 中的 Key 轉換成 Array,然後再運用 Array (forEach, map) 進行 loop.
// 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
var nameObj = {first: "Zaphod", last: "Beeblebrox"};
Object.keys(nameObj).forEach(function(key) {
console.log(key + ': ' + nameObj[key]);
});
// 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);
PLACEHOLD.IT
PlaceIMG
Unsplash It
THE WIRE QUOTE GENERATOR
Meet the Ipsums
Free HD Stock Video at Videezy
Document Outlines
Using HTML sections and outlines
How to mark up subheadings, subtitles, alternative titles and taglines
Navigation in Lists: To Be or Not To Be
Wrapup of Navigation in Lists
Htmlreference.io
What Web Can Do Today
Html5 Doctor
HTML5 Element FlowChart
HTML 5 Outliner
Markup Validation Service
Specificity Calculator
Using data attributes
STYLE TILES
BEM
Naming
idiomatic-css
airbnb css
Code Guide by @mdo
Normalize.css
Reset CSS
HTML5 Reset Stylesheet
How to structure a Sass project
Organizing Your CSS Code for Preprocessors
dancasttro/structure-css
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
// 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'] }
]
}
}
// .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
Frameworks
Assertion
Run without browser
End-to-End testing
獲取頁面加載監控數據 PerformanceTiming
DNS解析時間: domainLookupEnd - domainLookupStart
TCP建立連接時間: connectEnd - connectStart
白屏時間: responseStart - navigationStart
dom渲染完成時間: domContentLoadedEventEnd - navigationStart
頁面onload時間: loadEventEnd - navigationStart
# 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');
querySelectorAll 預設 return non array
可透過[]去訪問陣列的屬性 .forEach
取代 Array.prototype.forEach.call(...)
的簡易寫法
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(10)].map((d, i) => {
// do somethgin ....
return i;
});
透過 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
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");
- Let us to use next generation Javascript by Compiling it to ES5
# npm ls -g --depth 0
# npm install -g babel-cli
# babel --version
# npm init
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
### npm cache verify 垃圾收集不必要的數據
npm cache verify
### npm cache clean
npm cache clean --force
// 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)
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)
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
$('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;
}
});
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]);
}
}
}
};
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 app.js
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
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
使用 nodemon 執行 node 程式,檔案編修後 nodemon 會自動重新執行 node 程式
npm install -g nodemon
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.
Node >= 0.11.
$ npm install -g npm-check
$ npm-check
$('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;
});
$(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')
}
}
$('input[type="submit"]').attr("disabled", true);
$(‘input[type="submit"]').removeAttr("disabled”);
$('li:odd').css('background', ‘#e7e7e7’);
$(“a.disable").on("click", function(e){
e.preventDefault();
});
$(“.main”).toggleClass(“selected”);
$('img').error(function(){
$(this).attr('src', 'img/broken.png');
});
$("#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!')
});
$('.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>
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
npm install --save-dev cross-env
{
"scripts": {
"prod": "cross-env Version=1.0.1.1 node prod.js"
}
}
在 prod.js 中就能抓取到 'Version' 值
console.log(process.env.Version);
Reference
Install
// 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);
};
};
var searchInputFunc = debounce(function () {
var _val = $(this).val().trim();
console.log(_val);
// dosomething...
}, 500);
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);
}
};
}
$('body').on('mousemove', throttle(function (event) {
console.log('tick');
// dosomething...
}, 1000));
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.