My Function library

enter something useful

Pada tanggal 05 Maret 2016. Lihat %(latest_version_link).

Skrip ini tidak untuk dipasang secara langsung. Ini adalah pustaka skrip lain untuk disertakan dengan direktif meta // @require https://update.greasyforks.org/scripts/9160/111519/My%20Function%20library.js

"use strict";
//// ==UserScript==
// @name            My Function library
// @namespace       http://use.i.E.your.homepage/
// @version         0.35
// @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         2014-00-00
// @history         @version 0.25 - first version: public@released - 2015-04-12
// @history         @version 0.30 - Second version: public@released - 2015-12-10
// @history         @version 0.35 - Second version: public@released - 2016-03-04
// @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

/*
$("li").not(function() {
    // returns true for those elements with at least one span as child element
    return $(this).children('span').length > 0
}).each(function() { /* ...  })
*/


    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;
        },
        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');
        },
        /*        hasParent       : function( parentSelection ){
         return parentSelection.inElem('#') ? this.parent().hasId( parentSelection.split('#').shift() ) : this.parent().hasClass( parentSelection.split('.').shift() );
         },
         */
        hasNoChildren       : function ( element ) {
            return $( this ).filter( function(){ return !$( this ).children( element ).length; });
            //return !$( this ).children().length
        },
        hasParent           : function (e) {
            return !$( this ).parent(e).length
        },
        hasParents          : function (e) {
            return !$(this).parents(e).length
        },
        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);
        },
        src                 : function (newSRC) {
            return arguments.length === 0 ? this.attr('src') : this.attr('src', newSRC);
        },
        equals              : function (compareTo) {
            if (!compareTo || this.length != compareTo.length)
                return false;

            for (var i = 0; i < this.length; ++i) {
                if (this[i] !== compareTo[i])
                    return false;
            }
            return true;
        },
        justText            : function (newText) {
            var $children = null;
            if ( newText ) {
                $children = $( this )
                    .children()
                    .clone();
                $( this )
                    .children()
                    .remove()
                    .end()
                    .text( newText )
                    .prepend( $children );
                return $(this);
            }
            else {
                return $.trim( $( this )
                    .clone()
                    .children()
                    .remove()
                    .end()
                    .text());
            }
        }
    });

$.fn.ifExists = function( fn ) {
    this.length && fn( this );
};
/*
 $("#element").ifExists(
     function( $this ){
        $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
     });
 */
    $.fn.Exists = function( callback ) {
        var self = this;
        var wrapper = (function(){
            function notExists(){}
            notExists.prototype.ExistsNot = function( fallback ){
                !self.length && fallback.call(); };
            return new notExists;
        })();
        self.length && callback.call();
        return wrapper;
    };

    //And now i can write code like this -
/*    $("#elem").Exists(function(){
        alert ("it exists");
    }).ExistsNot(function(){
        alert ("it doesn't exist");
    });
*/
$.extend($.expr[":"], {
    ldata: function(el, idx, selector) {
        var attr = selector[3].split(", ");
        return el.dataset[attr[0]] === attr[1];
    },
    value: function(el, idx, selector) {
        return el.value === selector[selector.length - 1];
    }
});

    $.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());
        },
        data: $.expr.createPseudo ?
              $.expr.createPseudo(function( dataName ) {
                  return function( elem ) {
                      return !!$.data( elem, dataName );
                  };
              }) :
            // support: jQuery <1.8
              function( elem, i, match ) {
                  return !!$.data( elem, match[ 3 ] );
              }
    });
/*
$.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 autoCopyToClipboard( input ){
            $( 'body' ).append( $('<textarea/>',{ id:'copyThis', rows:"4", cols:"50", type:"text", value: input }) );
            $( '#copyThis').focus().select();
            document.execCommand("copy");
            $( '#copyThis' ).remove();
    }

    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;
    }

    Array.prototype.findArrayObj = function( find, value ){
        return this.filter(function( obj ){
            return obj[ find ] === value;
        })[0];
    };

    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;
    };

    // use full to convert String URL, so that you can use location commands
    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.capitalizeFirst = function(){
        return this.charAt(0).toUpperCase() + this.slice(1);
    };

    String.prototype.str2html = function(){
        return $('<div/>').html( this ).contents();
    };

//HTMLObjectElement.prototype.obj2Str = function(){var objArr = $.makeArray( this );return objArr[0].outerHTML;};

/*
    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;
        })();
    }

    function random( max ){
        var min = 1,
            rand = function(){
                return Math.floor( Math.random() * ( max - min + 1 ) + min );
            },
            num1 = rand(),
            num2 = rand();

        return ( num1 > num2 ? num2/num1 : num1/num2 ) * max;
    }

    function roundNearPeace( number, peaces, dec ) {
        return ( Math.round( number * peaces ) / peaces ).toFixed( dec );
    }

    function isFunction( functionToCheck ) {
        var getType = {};
        return functionToCheck && getType.toString.call( functionToCheck ) === '[object Function]';
    }

    //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 = $(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 )
*/

长期地址
遇到问题?请前往 GitHub 提 Issues。