高效coder,筹备开源框架toutou.escort.js

148 阅读5分钟

背景:JavaScript在工作中运用的非常广泛,作为一门弱类型语言,在使用JavaScript的时候,很多事情需要coder manual的去完成,这无疑增加了coder的工作量。

扩展:在这样的背景下,很多coder会将JavaScript一些需要自己manual去做的事情单独记录下来,以便在以后的工作中如果再遇到需要manual完成的工作可以轻松一些。

在工作中经常接触JavaScript,也就有了一些积累。就有了toutou.escort.js。即使她现在还不是很完善,也可能有很多问题无法解决。但是既然打算将她"造"出来,我就会在以后的工作 中不断的基类,让她不断的"丰满"起来。

v1.0 Summary

\

/**

 * toutou.escort.js -- js扩展的插件,可以有效的提高js效率,解决js中遇到的某些疑难杂症[注1],为你的程序保驾护航。

 *

 * @version 1.0

 * @author 头头哥

 * @requires None

 * @createDate 4/30/2014

 * @modifyDate 4/30/2014

 *

 * 注1: 可解决的某些疑难杂症如下(包含如下但不局限于如下,更多疑难杂症需要你的奇思妙想)

 * StringBuffer 高效率字符串拼接

 * uniqueescort 数组去重用的原型扩展,可以直接使用

 * 数组是否包含某一项

 * 数组删除制定项

 * isFilled/isEmpty字符串检测非空与空

 * format 将指定的 String类型的数据中的每个格式项替换为相应对象的值的文本等效项。  类似C# string.format()

 * 得到指定范围内的随机数

 * 获取JSON的属性  js本身没有反射机制,所以需要自己手动获取

 **/

v2.0 Details

2.1.0 StringBuffer

// 高效率字符串拼接

function StringBuffer ()  {

    this. _strings_ =  new Array ();

};

 

StringBuffer .prototype. append =  function  ( str )  {

    this. _strings_ . push ( str );

};

 

StringBuffer .prototype. toString =  function  ()  {

    return  this. _strings_ . join ( '' );

};

 

/*Example:

* var buffer = new StringBuffer();

* buffer.append("hello ");

* buffer.append("world");

* var result = buffer.toString(); */

2.1.1 代码分析

ECMAScript 中最常见的一个问题是字符串连接的性能。与其他语言类似,ECMAScript 的字符串是不可变的,即它们的值不能改变。请考虑下面的代码:

var str = "hello "; str += "world";

这段字符串拼接代码其实幕后执行的过程是这样的:

  1. 创建存储 "hello " 的字符串。
  2. 创建存储 "world" 的字符串。
  3. 创建存储连接结果的字符串。
  4. 把 str 的当前内容复制到结果中。
  5. 把 "world" 复制到结果中。
  6. 更新 str,使它指向结果。

每次完成字符串连接都会执行步骤 2 到 6,使得这种操作非常消耗资源。如果重复这一过程几百次,甚至几千次,就会造成性能问题。解决方法是用 Array 对象存储字符串,然后用 join() 方法(参数是空字符串)创建最后的字符串。

首先要注意的是 strings 属性,本意是私有属性。它只有两个方法,即 append() 和 toString() 方法。append() 方法有一个参数,它把该参数附加到字符串数组中,toString() 方法调用数组的 join 方法,返回真正连接成的字符串。

By the way: 以上部分解析来自书上,然后加了一些个人的理解把书上的内容简化了一部分。

2.2.0 uniqueescort

// 数组去重

Array .prototype. uniqueescort =  function  ()  {

    this. sort ();

    var re =  [this[ 0 ]];

    for  (var i **=**1 ; i <  this. length ; i ++)  {

        if  (this[ i ]  !== re [ re . length **-**1 ])  {

            re . push (this[ i ]);

        }

    }

    return re ;

};

 

/*Example:

* var a=[1,1,2,3,3];

* a=a.uniqueescort(); */

2.2.1 代码分析

JS数组去重百度一下一大堆解决方案,关于JS数组去重也有很多方案

这里我采取的方案是先将源数组排序,然后先建一个空数组,再将空数组与源数组的item逐一比较。若不存在,则push

2.3.0 contains

// 数组是否包含某一项  如果引用了jQuery的话,可以考虑使用$.inArray("item", arr)方法

if  (typeof Array .prototype. contains !=="function" )  {

    Array .prototype. contains =  function  ( item )  {

        return  this. indexOf ( item )  ==  **-**1 ?  false  :  true;

    };

}

 

// 这里判断是否已经存在Array.contains()方法还可以使用 Array.prototype.contains = Array.prototype.contains || function(item) {...}; 看自己取舍吧。

/*Example:

* var a=[1,1,2,3,3];

* a=a.contains(3); true */

2.3.1 代码分析

if (typeof Array.prototype.contains !== "function") {这里之所以有这个判断,是为了防止用原型覆盖了其它引用JS已经存在的contains方法。

一般在用原型的时候,对于可能容易引起"撞衫"的函数名,最好加个这样的判断或者是将名字命的"个性"一点。当然也可以选择就用传统命名,然后原型之前判断一下。

2.4.0 remove

// 数组删除指定项

if  (typeof Array .prototype. remove !=="function" )  {

    Array .prototype. remove =  function  ( item , isRemoveAll )  {

        var index =  this. indexOf ( item );

        if  ( index >  **-**1 )  {

            this. splice ( index , 1 );

            if  ( isRemoveAll && index >  **-**1 )  {

                this. remove ( item , isRemoveAll );

            }

        }

 

        return  this;

    };

}

2.4.1 代码分析

从2.4方法开始,对于比较显而易见的代码段将不再做代码分析,下同。

2.5 isFilled && isEmpty

// 字符串检测非空与空

String .prototype. isFilled =  function  ()  {

    return  this  &&  this. length > 0 ;

};

 

String .prototype. isEmpty =  function  ()  {

    return  !this. IsFilled ();

};

 

/*Example:

* var a="1"

* console.log(a.IsFilled());  result: true*/

2.6 format

// 类似C# string.format()

if  (typeof String .prototype. format !=="function" )  {

    String .prototype. format =  function  ()  {

        var args = arguments ;

        return  this. replace (/{(\d+)}/g,  function  ( match , number )  {

            return  typeof args [ number ]  !='undefined' ? args [ number ]  : match ;

        });

    }

}

 

/*Example:

* var a="{0}的{1}说翻{2}翻"

* console.log(a.format('友谊','小船','就'));  result: 友谊的小船说翻就翻*/

2.7 randomize

// 得到指定范围内的随机数

function randomize ( min , max )  {

    return Math . floor ( Math . random ()  *  ( max - min + 1 )  + min );

}

 

/*Example:

* var a=randomize(1,100);

* console.log(a);*/

2.8 GetProperties

// 获取JSON的属性

function GetProperties ( json )  {

    var properties =  [];

    for  (var prop in json )  {

        properties [ properties . length ]  = prop ;

    }

 

    return properties ;

}

 

/*Example:

var a = { 'id': '1', 'name': 'ming', 'info': 'like', 'pwd': '123', 'date': '4-20-2016' };

var aa = GetProperties(a);*/

v3.0 Summarize

在前言部分已经说了,这篇博文只是为了筹备toutou.escort.js这么一个开源工具,这里列举的一些 扩展方法或者类也只算是一个抛砖引玉吧。在以后的工作中,如果再有积累的东西,会继续更新到这篇博文,以及对应的更新toutou.escort.jsGithub。如果广大园友愿意给出平常自己积累的一些小扩展的东西,可以在下方评论或者私信我。


作  者:请叫我头头哥
出  处:www.cnblogs.com/toutou/
关于作者:专注于基础平台的项目开发。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角 推荐 一下。您的鼓励是作者坚持原创和持续写作的最大动力!\