Dev: Update util library

This commit is contained in:
surunzi
2017-08-11 08:40:27 +08:00
parent a473191f1e
commit c600279015
4 changed files with 196 additions and 138 deletions

View File

@@ -301,7 +301,7 @@ var People = Class({
},
introduce: function ()
{
return 'I am ' + this.name + ', ' + this.age + ' years old.'.
return 'I am ' + this.name + ', ' + this.age + ' years old.';
}
});
@@ -314,7 +314,7 @@ var Student = People.extend({
},
introduce: function ()
{
return this.callSuper(People, 'introduce') + '\n I study at ' + this.school + '.'.
return this.callSuper(People, 'introduce') + '\n I study at ' + this.school + '.';
}
}, {
is: function (obj)
@@ -828,6 +828,23 @@ Like extend, but only copies own properties over to the destination object.
extendOwn({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24}
```
## fileSize
Turn bytes into human readable file size.
|Name |Type |Desc |
|------|------|------------------|
|bytes |number|File bytes |
|return|string|Readable file size|
```javascript
fileSize(5); // -> '5'
fileSize(1500); // -> '1.46K'
fileSize(1500000); // -> '1.43M'
fileSize(1500000000); // -> '1.4G'
fileSize(1500000000000); // -> '1.36T'
```
## filter
Iterates over elements of collection, returning an array of all the values that pass a truth test.
@@ -848,11 +865,13 @@ filter([1, 2, 3, 4, 5], function (val)
## getFileName
No documentation.
dependencies
last trim
## getObjType
No documentation.
dependencies
upperFirst
## has
@@ -995,7 +1014,8 @@ console.log(isBrowser); // -> true if running in a browser
## isCrossOrig
No documentation.
dependencies
startWith
## isDate
@@ -1379,17 +1399,18 @@ Used for function context binding.
## orientation
No documentation.
dependencies
Emitter
## partial
Partially apply a function by filling in given arguments.
|Name |Type |Desc |
|--------|--------|----------------------------------------|
|fn |function|Function to partially apply arguments to|
|partials|...* |Arguments to be partially applied |
|return |function|New partially applied function |
|Name |Type |Desc |
|-----------|--------|----------------------------------------|
|fn |function|Function to partially apply arguments to|
|...partials|* |Arguments to be partially applied |
|return |function|New partially applied function |
```javascript
var sub5 = partial(function (a, b) { return b - a }, 5);
@@ -1398,7 +1419,8 @@ sub(20); // -> 15
## pxToNum
No documentation.
dependencies
toNum
## query
@@ -1498,7 +1520,8 @@ safeGet(obj, 'a.b'); // -> undefined
## safeStorage
No documentation.
dependencies
isUndef memStorage
## slice

View File

@@ -17,7 +17,7 @@ export default class Network extends Tool
this._requests = {};
this._tpl = require('./Network.hbs');
var performance = this._performance = window.webkitPerformance || window.performance;
let performance = this._performance = window.webkitPerformance || window.performance;
this._hasResourceTiming = performance && util.isFn(performance.getEntries);
}
init($el, parent)
@@ -36,18 +36,18 @@ export default class Network extends Tool
}
overrideXhr()
{
var winXhrProto = window.XMLHttpRequest.prototype;
let winXhrProto = window.XMLHttpRequest.prototype;
var origSend = this._origSend = winXhrProto.send,
let origSend = this._origSend = winXhrProto.send,
origOpen = this._origOpen = winXhrProto.open;
var self = this;
let self = this;
winXhrProto.open = function (method, url)
{
var xhr = this;
let xhr = this;
var req = xhr.erudaRequest = new Request(xhr, method, url);
let req = xhr.erudaRequest = new Request(xhr, method, url);
req.on('send', (id, data) => self._addReq(id, data));
req.on('update', (id, data) => self._updateReq(id, data));
@@ -66,7 +66,7 @@ export default class Network extends Tool
winXhrProto.send = function (data)
{
var req = this.erudaRequest;
let req = this.erudaRequest;
if (req) req.handleSend(data);
origSend.apply(this, arguments);
@@ -74,7 +74,7 @@ export default class Network extends Tool
}
restoreXhr()
{
var winXhrProto = window.XMLHttpRequest.prototype;
let winXhrProto = window.XMLHttpRequest.prototype;
if (this._origOpen) winXhrProto.open = this._origOpen;
if (this._origSend) winXhrProto.send = this._origSend;
@@ -104,7 +104,7 @@ export default class Network extends Tool
}
_updateReq(id, data)
{
var target = this._requests[id];
let target = this._requests[id];
if (!target) return;
@@ -119,17 +119,17 @@ export default class Network extends Tool
}
_bindEvent()
{
var $el = this._$el,
let $el = this._$el,
parent = this._parent;
var self = this;
let self = this;
$el.on('click', '.eruda-performance-timing', function ()
{
$el.find('.eruda-performance-timing-data').show();
}).on('click', '.eruda-request', function ()
{
var id = util.$(this).data('id'),
let id = util.$(this).data('id'),
data = self._requests[id];
if (!data.done) return;
@@ -144,7 +144,7 @@ export default class Network extends Tool
});
}).on('click', '.eruda-entry', function ()
{
var idx = util.$(this).data('idx'),
let idx = util.$(this).data('idx'),
data = self._resourceTimingData[Number(idx)];
if (data.initiatorType === 'img')
@@ -159,7 +159,7 @@ export default class Network extends Tool
function showSources(type, data)
{
var sources = parent.get('sources');
let sources = parent.get('sources');
if (!sources) return;
sources.set(type, data);
@@ -169,16 +169,16 @@ export default class Network extends Tool
}
_getPerformanceTimingData()
{
var performance = this._performance;
let performance = this._performance;
if (!performance) return;
var timing = performance.timing;
let timing = performance.timing;
var data = [];
let data = [];
/* eslint-disable no-unused-vars */
var {
let {
navigationStart,
unloadEventStart,
unloadEventEnd,
@@ -202,13 +202,13 @@ export default class Network extends Tool
loadEventEnd
} = timing;
var start = navigationStart,
let start = navigationStart,
end = loadEventEnd,
total = end - start;
function getData(name, startTime, endTime)
{
var duration = endTime - startTime;
let duration = endTime - startTime;
return {
name: name,
@@ -233,7 +233,7 @@ export default class Network extends Tool
this._performanceTimingData = data;
var performanceTiming = {};
let performanceTiming = {};
[
'navigationStart',
'unloadEventStart',
@@ -266,7 +266,7 @@ export default class Network extends Tool
{
if (!this._hasResourceTiming) return;
var entries = this._performance.getEntries(),
let entries = this._performance.getEntries(),
hideXhr = this.config.get('hideXhrResource'),
data = [];
@@ -286,7 +286,7 @@ export default class Network extends Tool
}
_initCfg()
{
var cfg = this.config = util.createCfg('network');
let cfg = this.config = util.createCfg('network');
cfg.set(util.defaults(cfg.get(), {
disablePerformance: false,
@@ -304,7 +304,7 @@ export default class Network extends Tool
}
});
var settings = this._parent.get('settings');
let settings = this._parent.get('settings');
settings.text('Network')
.switch(cfg, 'overrideXhr', 'Catch Xhr Requests');
@@ -317,11 +317,11 @@ export default class Network extends Tool
{
if (!this.active) return;
var cfg = this.config;
let cfg = this.config;
this._getResourceTimingData();
var renderData = {entries: this._resourceTimingData};
let renderData = {entries: this._resourceTimingData};
if (cfg.get('overrideXhr'))
{

View File

@@ -25,9 +25,9 @@ export default class Request extends util.Emitter
}
handleHeadersReceived()
{
var xhr = this._xhr;
let xhr = this._xhr;
var type = getType(xhr.getResponseHeader('Content-Type'));
let type = getType(xhr.getResponseHeader('Content-Type'));
this.emit('update', this._id, {
type: type.type,
@@ -39,10 +39,10 @@ export default class Request extends util.Emitter
}
handleDone()
{
var xhr = this._xhr,
let xhr = this._xhr,
resType = xhr.responseType;
var resTxt = (resType === '' || resType === 'text') ? xhr.responseText : '';
let resTxt = (resType === '' || resType === 'text') ? xhr.responseText : '';
this.emit('update', this._id, {
status: xhr.status,
@@ -56,10 +56,10 @@ export default class Request extends util.Emitter
function getHeaders(xhr)
{
var raw = xhr.getAllResponseHeaders(),
let raw = xhr.getAllResponseHeaders(),
lines = raw.split('\n');
var ret = {};
let ret = {};
util.each(lines, (line) =>
{
@@ -67,7 +67,7 @@ function getHeaders(xhr)
if (line === '') return;
var [key, val] = line.split(':', 2);
let [key, val] = line.split(':', 2);
ret[key] = util.trim(val);
});
@@ -79,7 +79,7 @@ function getType(contentType)
{
if (!contentType) return 'unknown';
var type = contentType.split(';')[0].split('/');
let type = contentType.split(';')[0].split('/');
return {
type: type[0],
@@ -89,14 +89,14 @@ function getType(contentType)
function getSize(xhr, headersOnly, url)
{
var size = 0;
let size = 0;
function getStrSize()
{
if (!headersOnly)
{
var resType = xhr.responseType;
var resTxt = (resType === '' || resType === 'text') ? xhr.responseText : '';
let resType = xhr.responseType;
let resTxt = (resType === '' || resType === 'text') ? xhr.responseText : '';
if (resTxt) size = lenToUtf8Bytes(resTxt);
}
}
@@ -116,19 +116,17 @@ function getSize(xhr, headersOnly, url)
if (size === 0) getStrSize();
if (size < 1024) return size + 'B';
return (size / 1024).toFixed(1) + 'KB';
return `${util.fileSize(size)}B`;
}
function lenToUtf8Bytes(str)
{
var m = encodeURIComponent(str).match(/%[89ABab]/g);
let m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
var origin = window.location.origin;
let origin = window.location.origin;
function fullUrl(url)
{

View File

@@ -698,6 +698,41 @@ module.exports = (function ()
return exports;
})();
/* ------------------------------ fileSize ------------------------------ */
_.fileSize = (function ()
{
/* Turn bytes into human readable file size.
*
* |Name |Type |Desc |
* |------|------|------------------|
* |bytes |number|File bytes |
* |return|string|Readable file size|
*
* ```javascript
* fileSize(5); // -> '5'
* fileSize(1500); // -> '1.46K'
* fileSize(1500000); // -> '1.43M'
* fileSize(1500000000); // -> '1.4G'
* fileSize(1500000000000); // -> '1.36T'
* ```
*/
function exports(bytes)
{
if (bytes <= 0) return '0';
var suffixIdx = Math.floor(Math.log(bytes) / Math.log(1024)),
val = bytes / Math.pow(2, suffixIdx * 10);
return +val.toFixed(2) + suffixList[suffixIdx];
}
var suffixList = ['', 'K', 'M', 'G', 'T'];
return exports;
})();
/* ------------------------------ upperFirst ------------------------------ */
var upperFirst = _.upperFirst = (function ()
@@ -822,6 +857,35 @@ module.exports = (function ()
return exports;
})();
/* ------------------------------ isArr ------------------------------ */
var isArr = _.isArr = (function (exports)
{
/* Check if value is an `Array` object.
*
* |Name |Type |Desc |
* |------|-------|----------------------------------|
* |val |* |The value to check |
* |return|boolean|True if value is an `Array` object|
*
* ```javascript
* isArr([]); // -> true
* isArr({}); // -> false
* ```
*/
/* dependencies
* objToStr
*/
exports = Array.isArray || function (val)
{
return objToStr(val) === '[object Array]';
};
return exports;
})({});
/* ------------------------------ isDate ------------------------------ */
var isDate = _.isDate = (function ()
@@ -1316,6 +1380,43 @@ module.exports = (function ()
return exports;
})();
/* ------------------------------ isEmpty ------------------------------ */
var isEmpty = _.isEmpty = (function ()
{
/* Check if value is an empty object or array.
*
* |Name |Type |Desc |
* |------|-------|----------------------|
* |val |* |Value to check |
* |return|boolean|True if value is empty|
*
* ```javascript
* isEmpty([]); // -> true
* isEmpty({}); // -> true
* isEmpty(''); // -> true
* ```
*/
/* dependencies
* isArrLike isArr isStr isArgs keys
*/
function exports(val)
{
if (val == null) return true;
if (isArrLike(val) && (isArr(val) || isStr(val) || isArgs(val)))
{
return val.length === 0;
}
return keys(val).length === 0;
}
return exports;
})();
/* ------------------------------ safeGet ------------------------------ */
var safeGet = _.safeGet = (function ()
@@ -1359,72 +1460,6 @@ module.exports = (function ()
return exports;
})();
/* ------------------------------ isArr ------------------------------ */
var isArr = _.isArr = (function (exports)
{
/* Check if value is an `Array` object.
*
* |Name |Type |Desc |
* |------|-------|----------------------------------|
* |val |* |The value to check |
* |return|boolean|True if value is an `Array` object|
*
* ```javascript
* isArr([]); // -> true
* isArr({}); // -> false
* ```
*/
/* dependencies
* objToStr
*/
exports = Array.isArray || function (val)
{
return objToStr(val) === '[object Array]';
};
return exports;
})({});
/* ------------------------------ isEmpty ------------------------------ */
var isEmpty = _.isEmpty = (function ()
{
/* Check if value is an empty object or array.
*
* |Name |Type |Desc |
* |------|-------|----------------------|
* |val |* |Value to check |
* |return|boolean|True if value is empty|
*
* ```javascript
* isEmpty([]); // -> true
* isEmpty({}); // -> true
* isEmpty(''); // -> true
* ```
*/
/* dependencies
* isArrLike isArr isStr isArgs keys
*/
function exports(val)
{
if (val == null) return true;
if (isArrLike(val) && (isArr(val) || isStr(val) || isArgs(val)))
{
return val.length === 0;
}
return keys(val).length === 0;
}
return exports;
})();
/* ------------------------------ isBool ------------------------------ */
_.isBool = (function ()
@@ -1668,7 +1703,7 @@ module.exports = (function ()
*/
var regMobileAll = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i,
regMobileFour = /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i;
regMobileFour = /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i;
exports = memoize(function (ua)
{
@@ -1829,11 +1864,13 @@ module.exports = (function ()
*/
/* dependencies
* repeat
* repeat toStr
*/
function exports(str, len, chars)
{
str = toStr(str);
var strLen = str.length;
chars = chars || ' ';
@@ -2277,7 +2314,7 @@ module.exports = (function ()
* },
* introduce: function ()
* {
* return 'I am ' + this.name + ', ' + this.age + ' years old.'.
* return 'I am ' + this.name + ', ' + this.age + ' years old.';
* }
* });
*
@@ -2290,7 +2327,7 @@ module.exports = (function ()
* },
* introduce: function ()
* {
* return this.callSuper(People, 'introduce') + '\n I study at ' + this.school + '.'.
* return this.callSuper(People, 'introduce') + '\n I study at ' + this.school + '.';
* }
* }, {
* is: function (obj)
@@ -2690,7 +2727,7 @@ module.exports = (function ()
function getCss(node, name)
{
return node.style[camelCase(name)];
return node.style[camelCase(name)] || getComputedStyle(node, '').getPropertyValue(name);
}
function setCss(nodes, css)
@@ -3034,7 +3071,7 @@ module.exports = (function ()
handler,
handlerQueue = formatHandlers.call(this, e, handlers);
e = new delegate.Event(e);
e = new exports.Event(e);
var i = 0, j, matched, ret;
@@ -3058,7 +3095,7 @@ module.exports = (function ()
function formatHandlers(e, handlers)
{
var current = e.target,
ret = [],
ret = [],
delegateCount = handlers.delegateCount,
selector, matches, handler, i;
@@ -3097,7 +3134,7 @@ module.exports = (function ()
{
var handler = {
selector: selector,
handler : fn
handler: fn
},
handlers;
@@ -3380,7 +3417,7 @@ module.exports = (function ()
function safeName(name)
{
return isStr(name) ? name.split(/\s/) : toArr(name);
return isStr(name) ? name.split(/\s+/) : toArr(name);
}
return exports;
@@ -3749,11 +3786,11 @@ module.exports = (function ()
{
/* Partially apply a function by filling in given arguments.
*
* |Name |Type |Desc |
* |--------|--------|----------------------------------------|
* |fn |function|Function to partially apply arguments to|
* |partials|...* |Arguments to be partially applied |
* |return |function|New partially applied function |
* |Name |Type |Desc |
* |-----------|--------|----------------------------------------|
* |fn |function|Function to partially apply arguments to|
* |...partials|* |Arguments to be partially applied |
* |return |function|New partially applied function |
*
* ```javascript
* var sub5 = partial(function (a, b) { return b - a }, 5);
@@ -3905,7 +3942,7 @@ module.exports = (function ()
{
each(['on', 'off', 'once', 'emit'], function (val)
{
obj[val] = Emitter.prototype[val];
obj[val] = exports.prototype[val];
});
obj._events = obj._events || {};
@@ -4261,7 +4298,7 @@ module.exports = (function ()
*/
/* dependencies
* Class extend trim query isEmpty each toArr
* Class extend trim query isEmpty each isArr toArr
*/
exports = Class({