My Function library

enter something useful

目前為 2015-12-10 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/9160/93168/My%20Function%20library.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

"use strict";
//// ==UserScript==
// @name            My Function library
// @namespace       http://use.i.E.your.homepage/
// @version         0.30
// @description     enter something useful
// @grant           GM_getValue
// @grant           GM_setValue
// @grant           GM_deleteValue
// @run-at          document-start

// @created         2015-04-06
// @released        2014-00-00
// @updated         2015-12-10
// @history         @version 0.25 - first version: public@released - 2015-04-12
// @history         @version 0.30 - first version: public@released - 2015-12-10
// @compatible      Greasemonkey, Tampermonkey
// @license         GNU GPL v3 (http://www.gnu.org/copyleft/gpl.html)
// @copyright       2014+, Magnus Fohlström
// ==/UserScript==

/*global $, jQuery*/
/*jshint -W014, -W030, -W082*/
// -W014, laxbreak, Bad line breaking before '+'
// -W030, Expected assignment or function call instead saw an expression
// -W082, a function declaration inside a block statement

    window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
        console.debug('Error: ' + errorMsg + '\nScript: ' + url + '\nLine: ' + lineNumber
        + '\nColumn: ' + column + '\nStackTrace: ' +  errorObj);
    };
    /**
    *  @namespace waitUntilExists_Intervals
    */
    $.fn.waitUntilExists = function (handler, shouldRunHandlerOnce, isChild){
        var found	= 'found',
            $this	= $(this.selector),
            $elements	= $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);
        if( !isChild ) {
            (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
                window.setInterval(function () {
                    $this.waitUntilExists(
                        handler, shouldRunHandlerOnce, true);
                }, 500);
        }
        else if (shouldRunHandlerOnce && $elements.length){
            window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
        }
        return $this;
    };
    $.fn.extend({
        exists          : function(){
            return this.length === 0 ? 0 : this.length;
        },
        swapClass       : function( replace, newClass ){
            this.className.replace(replace, newClass);
        },
        toggleClasses   : function( add, remove, if_none ){
            var $this = $( this.selector );
            if_none !== undefined && !$this.hasClass( add ) && !$this.hasClass( remove ) && $this.addClass( if_none );
            $this.addClass( add ).removeClass( remove );
        },
        hasId           : function( id ){
            return id === this.attr('id');
        },
        hasQuery        : function( query ){
            return d.querySelector( query ).length;
        },
        isTag           : function( tag ){
            var e = this[0] || $('<undefined/>');
            //noinspection JSValidateTypes
            return e.nodeName !== undefined && e.nodeName.toLowerCase() === tag.toLowerCase();
        },
        isNode          : function( node ){
            var e = this[0] || $('<undefined/>');
            //noinspection JSValidateTypes
            return e.nodeName !== undefined && e.nodeName.toLowerCase() === node.toLowerCase();
        },
        attrs           : function( search, type, chklen ){ //bool name value length or 1 2 3 4
            var attribs = this[0].attributes;
            c.i('attribs',attribs)
            if( arguments.length === 0 ) {
                var obj = {};
                $.each( attribs, function(){
                    this.specified  && ( obj[ this.name ] = this.value );
                });
                return obj;
            } else if( search != undefined ) {
                var name = '', val = '';
                $.each( attribs, function(){
                    if( this.specified && type == 'length' ){
                        if( this.name.length > chklen ){
                            name = this.name;
                            return false;
                        }
                    }
                    else if( this.specified && this.name.inElem( search ) ){
                        name = this.name;
                        val = this.value;
                        return false;
                    }
                });
                return ( type == 'bool'   || type == 1) ?  name.length ? true : false :
                       ( type == 'name'   || type == 2) ?  name :
                       ( type == 'value'  || type == 3) ?  val :
                       ( type == 'length' || type == 4) && name;
            }
        },
        findClass       : function( Class ){
            return this.find('.' + Class )
        },
        href		    : function( newURL ){
            return arguments.length === 0 ? this.attr('href') : this.attr('href', newURL );
        }
    });


    $.extend({
        confirm: function (title, message, yesText, noText, yesCallback) {
            //dialog needs jQueryUI
            $("<div></div>").dialog( {
                buttons: [{
                    text: yesText,
                    click: function() {
                        yesCallback();
                        $( this ).remove();
                    }
                },
                    {
                        text: noText,
                        click: function() {
                            $( this ).remove();
                        }
                    }
                ],
                close: function (event, ui) { $(this).remove(); },
                resizable: false,
                title: title,
                modal: true
            }).text(message).parent().addClass("alert");
        }
    });
    $.extend($.expr[':'], {
        isEmptyTrimmed: function(el){
            return !$.trim($(el).html());
        }
    });

/*
$.confirm(
    "CONFIRM", //title
    "Delete " + filename + "?", //message
    "Delete", //button text
    deleteOk //"yes" callback
);
*/

    //ScrollZoomTune("div.thumb .title a",1,-25,1,'slow');
    function ScrollZoomTune(selection, zooms, tune, ani, speed){
        var body = $('body'), sel = $( selection), position;
        //noinspection JSValidateTypes
        sel.size() !== 0 && (
            body.css('zoom',zooms),
            position = sel.position().top + tune,
            ani === 1 ?
                body.animate({ scrollTop: position * zooms }, speed ) :
                body.scrollTop( position * zooms )
        );
    }

    function inURL( search ){
        var winLoc = window.location.href;
        return winLoc.search(search) !== -1;
    }

    function loadDoc( href ){
        $(location).attr('href', href );
    }

    function checkDividedIsInteger( num, div ){
        return ( num % div === 0 );
    }

    function isEven( value ){
        return ( value % 2 === 0 );
    }

    function fn_arrayElemExistsInDom( array ) {
        var found = false;
        jQuery.each( array, function( i, value ) {
            $( value ).length && ( found = true );
        });
        return found;
    }

    function toggleClassState( config, Class, state, elem ){
        config[ Class ] = typeof state === 'string' ? !config[ Class ] : state;
        $( elem || 'html' )[ config[ Class ] ? 'addClass' : 'removeClass' ]( Class );
    }

    function wrapWithTag( tag, text, selection ){
        var thisAttr = selection !== undefined && selection.startsWith('.') ? 'class' : selection.startsWith('#') && 'id',
            thisTag = $('<' + tag + '/>', { text: text });
        return thisAttr.length ? thisTag.attr( thisAttr, selection.splice( 1 ) ) : thisTag;
    }

    // will return true if the value is a primitive value
    function isPrimitiveType( value ){
        switch ( typeof value ) {
            case 'string': case 'number': case 'boolean': case 'undefined': {
                return true;
            }
            case 'object': {
                return !value;
            }
        }
        return false;
    }

    String.prototype.advSplit = function(chr,nbr) {
        var str = this.split(chr),
            strLen = str.length,
            chrLen = chr.length,
            newStr = ['',''],
            newArr = [];

        $.each( str, function( index ) {
            newStr[ index < nbr ? 0 : 1 ] += str[ index ] + chr;
        });

        $.each( newStr, function( index ) {
            newStr[ index ] = newStr[ index ].slice(0, - chrLen);
            newStr[ index ].length > 0 && newArr.push( newStr[ index]  );
        });

        return newArr;
    };

    String.prototype.advSplitJoin = function(chr,nbr,ips) {

        var str = this.split(chr),
            strLen = str.length,
            ipsLen = ips.length,
            newStr = '',
            newStrLen;

        $.each( str, function( index ) {
            var add = index < strLen - 1 ? chr : '';
            newStr += index + 1 === nbr ? str[index] + ips : str[index] + add;
        });

        newStrLen = newStr.length;
        newStr.slice( newStrLen - ipsLen ) === ips && ( newStr = newStr.slice( 0, newStrLen - ipsLen ) );

        return newStr;
    };

    String.prototype.lpad = function(padString, length) {
        var str = this;
        while ( str.length < length ) {
            str = padString + str; }
        return str;
    };

    String.prototype.reduceWhiteSpace = function() {
        return this.replace(/\s+/g, ' ');
    };

    String.prototype.formatString = function(){
        return this.toString()
            .split('!').join(' !').split('!;').join("!important;")
            .split(/\s+/g).join(' ')
            .split('{').join('{\n\t')
            .split('; ').join(';')

            .split('( ').join('(')
            .split(' )').join(')')

            .split(';').join(';\n\t')
            .split('*/').join('*/\n')
            .split(')*(').join(') * (')
            .split('}').join('}\n');
};

    String.prototype.inURL = function(){
        var winLoc = window.location.href;
        return winLoc.search(this) !== -1;
    };

    String.prototype.inString = function(string){
        return string !== undefined ? string.search(this) !== -1 : false;
    };

    String.prototype.inElem = function(search){
        return this !== undefined ? this.search(search) !== -1 : false;
    };

    String.prototype.undef = function(replace){
        return this === undefined ? replace : this;
    };

    String.prototype.extract = function( startChar, endChar, inside ){
        var str = this,
            startCharIndex = str.indexOf( startChar ),
            endCharIndex = str.indexOf( endChar );

        str = ( inside === 'yes' || inside === 1 || inside === true || inside === 'inside' ) ?
            str.replace( startChar, '').replace( endChar, '') : str.substr( startCharIndex, endCharIndex);

        return str;
    };

    String.prototype.toLocation = function() {
        var a = document.createElement('a');
        a.href = this;
        return a;
    };

    String.prototype.count = function( char, UpperCase ) {
        var numberOf = this.toString().match( new RegExp( char, ( UpperCase ? "gi" : "g" ) ) );
        return numberOf !== null ? numberOf.length : 0;
    };

    String.prototype.startsWith = function( str ){
        return this.slice(0, str.length) == str;
    };

    String.prototype.endsWith = function( str ){
        return this.slice(-str.length) == str;
    };

/*
    String.prototype.replaceAll = function( target, replacement ) {
        return this.split(target).join(replacement);
    };
*/

    /**
     * @return {string}
     */
    function Undefined(check,replace){
        return check === undefined ? replace.toString() : check.toString();
    }

    function GM_lister( remove ){
        var keys = GM_listValues();
        for (var i = 0, key = null; key = keys[i]; i++) {
            GM_listValues()[i] !== undefined && c.i('GM_ListItem: ' + GM_listValues()[i] + ':', GM_getValue(key));
            ( remove === true || remove === 'yes' || remove === 1 ) && GM_deleteValue(key);
        }
    }

    function filterClick( e, $this ){
        return e.which == 1 && e.target == $this;
    }

    function roundFloat(num,dec){
        var d = 1;
        for (var i=0; i<dec; i++){
            d += "0";
        }
        return Math.round(num * d) / d;
    }

    function randomFloatBetween( min, max, dec ){
        dec = typeof( dec ) == 'undefined' ? 2 : dec;
        return parseFloat( Math.min( min + ( Math.random() * ( max - min ) ), max ).toFixed( dec ) );
    }

    function refreshElement( elem , speed ){ //refreshElement('.videoPlayer','slow');
        var $elem = $( elem ), data = $elem.html();
        $elem.empty().html( data ).fadeIn( speed );
    }

    function getGlobal(){
        return (function(){
            return this;
        })();
    }

    //VideoTitleA("div.thumb .title a",'on');
    var VideoTitleA = function( elem , state ){
            $( elem ).each(function(){
            var $this    = $(this),
                strTitle = $this.attr('title'),
                strText  = $this.attr('data-text'),
                strHtml  = $this.text();
            state === 'on' ? $this.text(strTitle).attr('data-text',strHtml) : $this.text(strText);
        });
        },
        isNumeric   = function( value ){
            return /^\d+$/.test( value );
        },
        obj2Str     = function( obj ){
            var objArr = $.makeArray(obj);
            return objArr[0].outerHTML;
        },
        /**
         * @return {string}
         */
        MultiString = function(f){
            return f.toString().split('\n').slice(1, -1).join('\n');
        },
        w = window,
        glob = w,
        $w = $(w),
        $l = window.location,
        locDoc = window.location.href,
        d = document,
        $d = $(d),
        c = {
            defaultState: 3,
            cute : function( type, msg, color ) {
                color = color || "black";
                var newColor, bgc = "White";
                switch ( color ) {
                    case "success":  newColor = "Green";      bgc = "LimeGreen";       break;
                    case "info":     newColor = "DodgerBlue"; bgc = "Turquoise";       break;
                    case "error":    newColor = "Red";        bgc = "Black";           break;
                    case "start":    newColor = "OliveDrab";  bgc = "PaleGreen";       break;
                    case "warning":  newColor = "Tomato";     bgc = "Black";           break;
                    case "end":      newColor = "Orchid";     bgc = "MediumVioletRed"; break;
                    default: //noinspection SillyAssignmentJS
                        newColor = color;
                }

                typeof msg == "object" ?
                    window.console[ type ]( msg )
                : typeof color == "object" ? (
                    window.console[ type ]("%c" + msg, "color: PowderBlue;font-weight:bold; background-color: RoyalBlue;"),
                    window.console[ type ]( newColor )
                ):
                    window.console[ type ]("%c" + msg, "color:" + newColor + "; background-color: " + bgc + ";")
            },
            show: function( showThis, type ){
                var State = GM_getValue( type + 'StateValue' ) || this.defaultState;
                return showThis !== 0 && State !== 0 && State === ( showThis || State ) || State === 'all';
            },
            pre: function( type, name, fn, line, color ){
                line = line == undefined ? '' : line + ': ';
                var Fn = function(){ return fn !== undefined ? fn : ''; };
                typeof fn == "object" ?
                    window.console[ type ]( name, Fn() ) : c.cute( type, line + name + ': ' + Fn(), color );
            },
            l: function( name, fn, line, color, showThis ){
                var type = 'log';
                this.show( showThis, type ) && this.pre( type, name, fn, line, color );
            },
            h: function( name, fn, line, color, showThis ){
                var type = 'handled';
                this.show( showThis, type ) && this.pre( type, name, fn, line, color );
            },
            //c.l('name', 'fn'=='fn', 'line', 'blue')
            i: function( name, fn, line, color, showThis ){
                var type = 'info';
                this.show( showThis, type ) && this.pre( type, name, fn, line, color );
            },
            d: function( name, fn, line, color, showThis ){
                var type = 'debug';
                this.show( showThis, type ) && this.pre( type, name, fn, line, color );
            }
        },
        advTimer = {
            start   :   function( name, ms ){
                advTimer[name] = ms;
                setTimeout(function(){ advTimer[name] = 0; }, ms );
            },
            check   :   function( name ){
                advTimer[name] || ( advTimer[name] = 0 );
                return advTimer[name];
            },
            stop    :   function( name ){
                advTimer[name] = 0;
            }
        },
        g = {
            locDoc  : window.location.href,
            ms      : 0,
            timer   : function(ms){
                g.ms = ms;
                setTimeout(function(){ g.ms = 0; },ms);
            },
            lap     : {
                data : {},
                tid  : function(){ return performance.now(); },
                set  : function(name){ 			this.data[name] = this.tid();				},
                get  : function(name){ 			this.print(name); 							},
                end  : function(name){ 			this.print(name); 		this.del(name); 	},
                del  : function(name){   delete this.data[name];							},
                print: function(name){   c.i( name, this.tid() - this.data[name] + 'ms'); 	}
            },
            GM      : {
                engine : function( mode, val, range ){
                    switch (mode){
                        case 'set':     GM_setValue( val.name, val.default );
                            break;
                        case 'get':     range ? config[ val.name ] = GM_getValue( val.name ):
                                                ui.config[ val.name ] = GM_getValue( val.name );
                            break;
                        case 'del':     GM_deleteValue( val.name );
                    }
                },
                manager : function( mode, array, range ){
                    $.each( array, function( i, val ){ this.engine( mode, val, range === undefined ); });
                    mode === 'del' && ( GM_deleteValue( 'firstRun' ), GM_deleteValue( 'yourVer' ) );
                }
            }
        },
        testPerformance = function(name, fn, testCycles ) {
            g.lap.set( name );
            var i = 0;
            for ( i ; i < testCycles; i++ ){
                fn;
            }
            g.lap.end( name );
        };

    var perf = function (testName, fn) {
        var startTime = new Date().getTime();
        fn();
        var endTime = new Date().getTime();
        console.log(testName + ": " + (endTime - startTime) + "ms");
    };

$(document).on('click','*',function(e){
    this == e.target && c.i('target:', e.target ); });

c.i('my Function Library ö');
/*
isScrolledIntoView = (elem) ->
    docViewTop = $(window).scrollTop()
docViewBottom = docViewTop + $(window).height()
elemTop = $(elem).offset().top
elemBottom = elemTop + $(elem).height()

    (elemBottom - 200 < docViewBottom) and (elemBottom + $(elem).height() > docViewBottom )
*/