利用JavaScript常用的公共方法

/** 
* 获取字符串长度
*/
String.prototype.pointLength = function () {
    var len = 0;
    for (var i = 0; i < this.length;) {
        var codePoint = this.codePointAt(i);
        i += codePoint > 0xffff ? 2 : 1;
        len++;
    }
    return len;
}

/** 
* 获取字符串某个位置字符
*/
String.prototype.pointAt = function (index) {
    var curIndex = 0;//码点的下标
    for (var i = 0; i < this.length;) {
        var codePoint = this.codePointAt(i);
        if (curIndex === index) {
            return String.fromCodePoint(codePoint);
        }
        i += codePoint > 0xffff ? 2 : 1;
        curIndex++;
    }
}

/** 
* 获取字符串截取
*/
String.prototype.sliceByPoint = function (start, end) {
    if (start === undefined) start = 0;
    if (end === undefined) end = this.pointLength();
    var result = '';
    for (var i = start; i < end; i++) {
        result += this.pointAt(i);
    }
    return result;
}

/**
*是否Object对象
*@param val 值
*@return boolean
*/
jQuery.isObject = function (val) {
    if (typeof val === 'object' && val !== null) {
        return true;
    }
    return false;
}

/**
*是否相同
*@param val1 第一个值
*@param val2 第二个值
*@return boolean
*/
jQuery.isEquals = function (val1, val2) {
    if ($.isObject(val1) && $.isObject(val2)) {
        var keys1 = Object.keys(val1);
        var keys2 = Object.keys(val2);
        if (keys1.length !== keys2.length) {
            return false;
        }
        for (var i = 0; i < keys1.length; i++) {
            if (keys2.indexOf(keys1[i]) < 0) {
                return false;
            }
            if (!$.isEquals(val1[keys1[i]], val2[keys1[i]])) {
                return false;
            }
        }
        return true;
    } else {
        return val1 === val2;
    }
}

/**
*数组去重
*@param {Array} arr
*@return {Array}
*/
jQuery.uniqueArray = function (arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        var isFind = false;
        for (var j = 0; j < result.length; j++) {
            if ($.isEquals(result[j], arr[i])) {
                isFind = true;
                break;
            }
        }
        if (!isFind) {
            result.push(arr[i]);
        }
    }
    return result;
}

/**
*深度克隆
*@param value
*@return value
*/
jQuery.deepClone = function (value) {
    var cache = new WeakMap();
    function _deepClone(value) {
        if (typeof value !== 'object' || value === null) {
            return value;
        }
        if (cache.has(value)) {
            return cache.get(value);
        }
        var result = Array.isArray(value) ? [] : {};
        Object.setPrototypeOf(result, Object.getPrototypeOf(value));
        cache.set(value, result);
        for (key in value) {
            if (value.hasOwnProperty(key)) {
                result[key] = _deepClone(value[key]);
            }
        }
        return result;
    }
    return _deepClone(value);
}


/**
*  时间控件格式化
*  @param { String } target  控件ID
*  @param { String } datefromt  时间格式
*  @return { String } date 时间
*  @example inputEvents:$.myPluginWdatePickerDateFromt('wcnd','yyyy-MM-dd')"
*/
jQuery.myPluginWdatePickerDateFromt = function (target, datefromt) {
    if (!datefromt) datefromt = "yyyy-MM-dd HH:mm:ss";
    var handle = $.extend({}, $.fn.textbox.defaults.inputEvents, { click: function () {
        WdatePicker({
            onpicking: function (dp) {
                $("#" + target).textbox('setValue', dp.cal.getNewDateStr());
            },
            dateFmt: datefromt,
            onclearing: function (dp) {
                $("#" + target).textbox('setValue', '');
            }
        });
        WdatePicker({
            onpicking: function (dp) {
                $("#" + target).textbox('setValue', dp.cal.getNewDateStr());
            },
            dateFmt: datefromt,
            onclearing: function (dp) {
                $("#" + target).textbox('setValue', '');
            }
        });
    } 
    });
    return handle;
}

/**
*  函数管道,管道是将一个函数的输出直接发送到另一个函数
*/
jQuery.myPluginPipeLine = function () {
    var args = Array.from(arguments);
    return function (val) {
        return args.reduce(function (result, func) {
            return func(result);
        }, val);
    }
}

/**
*  柯里化函数,把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术
*/
jQuery.myPluginCurrying = function (func) {
    var args = Array.prototype.slice.call(arguments, 1); //得到从下标1开始的参数
    var that = this;
    return function () {
        var curArgs = Array.from(arguments); //当前调用的参数
        var totalArgs = args.concat(curArgs);
        if (totalArgs.length >= func.length) {
            return func.apply(null, totalArgs); //参数数量够了
        } else {
            //参数数量不够
            totalArgs.unshift(func);
            return $.myPluginCurrying.apply(that, totalArgs);
        }
    }
}

var _layerWidth = ($(window).width() + 100) + "px";
var _layerHeight = ($(window).height() + 80) + "px";

/**
*  获取datagrid的索引
*/
jQuery.myPluginRowIndex = function (target) {
    var tr = $(target).closest('tr.datagrid-row');
    return parseInt(tr.attr('datagrid-row-index'));
}

/**
*弹出框信息,传入最少3个参数
*@param { String } _target this获取的元素
*@param { String } _dg
*@param { String } _url
*@param { String } _title
*@param { Function } _fn
*@param { Object } _objdata
*@example $.myPluginOpenLayer(target, 'dg', url, '查看', info, research);$.myPluginOpenLayer(target, 'dg', url, '查看');$.myPluginOpenLayer('dg', url, '查看');
*/
jQuery.myPluginOpenLayer = function () {
    var args = Array.from(arguments);
    var _argsLength = args.length;
    if (_argsLength < 3) {
        throw new Error("At least three input parameters");
    }
    var _target = args[0];
    var _dg = args[1];
    var _url = args[2];
    var _title = args[3];
    var _fn = args[_argsLength - 1];
    var _objdata = args[_argsLength - 2];
    if (typeof _target !== 'object') {
        _target = null;
        _dg = args[0];
        _url = args[1];
        _title = args[2];
    }
    var _parameter = "";
    if (typeof _objdata === 'object' && _objdata !== null) {
        if (_target) {
            var _thisindex = $.myPluginRowIndex(_target);
            var _row = $("#" + _dg).datagrid('getRows')[_thisindex];
            $.each(_objdata, function (kk, vv) {
                _parameter += ((vv == "" ? (kk + "=" + _row[kk]) : (kk + "=" + vv))) + "&";
            });
        } else {
            $.each(_objdata, function (kk, vv) {
                _parameter += (kk + "=" + vv + "&");
            });
        }
    }
    if (_parameter != "") {
        _parameter = _parameter.slice(0, -1);
        _url = _url + "?" + _parameter;
    }
    parent.layer.open({
        type: 2,
        title: _title,
        area: [_layerWidth, _layerHeight],
        content: [_url],
        resize: true,
        maxmin: true,
        shadeClose: false,
        closeBtn: 1,
        end: function () {
            if (typeof _fn === "function") {
                _fn();
            }
        }
    });
}


/**
*函数重载
*@example var getuser = $.createOverload();
*getuser.addImpl('number', function (number) { console.log('number'); });
*getuser.addImpl('string', 'string', function (naem, sex) { console.log('two'); });
*/
jQuery.createOverload = function () {
    var callmap = new Map();
    function overload() {
        var args = Array.from(arguments);
        var key = args.map(function (arg) {
            return typeof arg;
        }).join(',');
        var fn = callmap.get(key);
        if (fn) {
            return fn.apply(this, args);
        } else {
            throw new Error("no matching function");
        }
    }
    overload.addImpl = function () {
        var args = Array.from(arguments);
        var fn = args.pop();
        if (typeof fn !== 'function') {
            return;
        }
        var types = args;
        callmap.set(types.join(','), fn);
    }
    return overload;
}

/**
*是否JSON字符
*@param { String } str
*@example $.isJsonCharacter(str)
*/
jQuery.isJsonCharacter = function (str) {
    if (typeof str === 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj === 'object' && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
}

/**
*Bind函数
*@param { String,Number,Object } this指向
@return { Function } function
*@example fn.myPluginBind('ctx',1,2);
*/
Function.prototype.myPluginBind = function (ctx) {
    var args = Array.prototype.slice.call(arguments, 1);
    var fn = this;
    return function _fnBind() {
        var restArgs = Array.prototype.slice.call(arguments);
        var allArgs = args.concat(restArgs);
        if (Object.getPrototypeOf(this) === _fnBind.prototype) {
            var obj = {};
            Object.setPrototypeOf(obj, fn.prototype);
            fn.apply(obj, allArgs);
            return obj;
        } else {
            return fn.apply(ctx, allArgs);
        }
    }
}

/**
*Call函数
*@param { String,Number,Object } this指向
@return { String,Number,Object } String,Number,Object
*@example fn.myPluginCall('ctx',1,2);
*/
Function.prototype.myPluginCall = function (ctx) {
    var args = Array.prototype.slice.call(arguments, 1);
    ctx = (ctx === undefined || ctx === null ? globalThis : Object(ctx));
    var fn = this;
    var key = Symbol('temp');
    Object.defineProperty(ctx, key, {
        enumerable: false,
        value: fn
    });
    var list = [];
    for (var i = 0; i < args.length; i++) {
        list[i] = 'args[' + i + ']';
    }
    var ret = eval('ctx[key](' + list.join(',') + ')');
    delete ctx[key];
    return ret;
}

/**
*生成[min,max]范围内的随机整数(大于等于min,小于等于max)
*@param { Number } min随机数区间最小值
*@param { Number } max随机数区间最大值
@return { Number } Number随机整数
*@example $.getRandomNumber(1, 3);
*/
jQuery.getRandomNumber = function (min, max) {
    return Math.floor(Math.random() * (max + 1 - min) + min);
}

你可能感兴趣的:(javascript,开发语言,ecmascript)