🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

flexargs

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

flexargs

解析函数输入参数,简化对多种传参的支持

latest
npmnpm
Version
1.0.4
Version published
Weekly downloads
2
-80%
Maintainers
1
Weekly downloads
 
Created
Source

当函数具备多个函数签名时,flexArgs可以方便地解析输入参数,使函数接受多种传参方式。

安装方法

   npm install flexargs

使用方法

import flexArgs from "flexargs"

 function myfunc(){
    // 对参数进行自动匹配和解析
    let { name, callback ,count,options } = flexArgs(
    [                                       // 定义5种传参方式
        {name:String},
        {count:Number},
        {name:String,options:Object},
        {name:String,callback:Function},
        {name:String,callback:Function,options:Object} 
    ],
    arguments,                              // 必须的
    {                                       // 可选的默认参数
        name:"tom",
        count:0,
        options:{x:2,z:9}
    })
    .....
 }

以上示例声明了myfunc函数支持5种传参方式,因此就可以非常任性也以如下方式调用myfunc:

//  name="aaa",count=0,callback=undefined,options:{x:2,z:9}
myfunc("aaa")                  
//  name="tom",count=1,callback=undefined,options:{x:2,z:9}
myfunc(1)                     
//  name="bbb",count=0,callback=undefined,options:{x:1,y:2,z:9}
myfunc("bbb",{x:1,y:2})        
//  name="ccc",count=0,callback=<function>,options:{x:2,z:9}
myfunc("ccc",function(){})     
//  name="ddd",count=0,callback=<function>,options:{x:1,y:2,z:9} 
myfunc("ddd",function(){},{x:1,y:2})    
 

同时也支持以下传参:

myfunc({name:"jack",count:1})

数据类型

指定数据类型时可以取值:

  • 字符串:numberstringfunctionany
  • 对象: ObjectStringNumberBooleanFunctionArray

字典传参

flexArgs可以通过位置参数进行匹配,当只有一个参数,且类型为Object时,采用字典传参匹配模式。

myfunc({name:"jack",count:1,options:{},callback:()==>{})

任意类型

参数类型增加any,可以指定某个参数的类型为any。如

 function myfunc(){
    let { name, payload,count } = flexArgs([              
        {name:String,payload:'any'}
        {name:String,count:Boolean}
    ],arguments)
 }
// 以下第三个参数,可以是任意类型
myfunc("a",1)
myfunc("a",true)
myfunc("a","wxzhang")
myfunc("a",{})

Keywords

argument

FAQs

Package last updated on 09 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts