IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    30行代码造了一个1494start项目的轮子

    Jarvin-Guan发表于 2016-05-02 15:34:18
    love 0

    本项目地址:argps 介绍:地址

    1494个start的项目:minimist

    30行代码轮子:argps

    项目功能:

    1. 解析命令行启动用户所输入的参数,转成Object。
    2. 需要支持多个命令、重复参数合并到数组、监测无名字参数合并到_中。

    Prower by Regex

    #index.js
    module.exports = function ( args ) {
        var result = {
            '_':[]
        };
     
        var value = args.join( ' ' );
        
        var reStr = /(-[^\s-](?:-\S+)?|--\S+)\s*([^\s-]*)?/g;
        
        var match;
        
        while( ( match = reStr.exec( value ) ) ) {
            var key = match[1].replace( /-/g,'' );
            match[2] = typeof match[2] === 'undefined' ? 'true' : match[2];
            if( key in result ) {
                if( result[key] instanceof Array ) {
                    result[key].push( match[2] );
                }else{
                    result[key] = new Array( result[key] , match[2] );
                }
            }else{
                result[key] = match[2];
            }
        }
        var _value = value.replace( /-[^-\s]{2,}|--?\S+\s*[^-\s]*/g,'' )
        .replace( /\s*^\s*|\s+$/g,'' )
        .split( /\s+/ );
        
        result._ = result._.concat( _value );
        return result;
    };
    


沪ICP备19023445号-2号
友情链接