amos-tool
by ilex.h
docs: docs
useage
npm install --save amos-tool
keywords
- amos ui
- amos tool
infos
api
| name | link | description | 
|---|---|---|
| Base64 | Base64 | base64加密解密 | 
| MD5 | MD5 | md5加密解密 | 
| DES | DES | des加密解密 | 
| Browser | Browser | 获取浏览器类型 | 
| deepCopy | deepCopy | 深度复制 | 
| deepEqual | deepEqual | 深度比较(stringify方式) | 
| fastDeepEqual | fastDeepEqual | 深度比较(循环) | 
| parseText | parseText | 替换或者补全url | 
| List | List | List集合 | 
| Queue | Queue | 队列 | 
| UUID | UUID | uuid | 
| browserSupport | browserSupport | 浏览器支持 | 
| Log | Log | 定制化的log日志 | 
| Store | Store | 数据处理,主要是localStorage、session、cookie | 
| LocationParam | LocationParam | location 工具 | 
| array2tree | array2tree | 将array转化为tree数据 | 
| tableFilter | tableFilter | 表格数据过滤 | 
| pwdPolicy | pwdPolicy | 密码生成器 | 
| omit | omit | omit操作,删除object中的键 | 
| pick | pick | pick操作,获取object指定key组成的新对象 | 
| utils | utils | 常用工具 | 
| xss | utils | xss 工具及 | 
| strUtils | strUtils | string常用工具 | 
| other | other | 其它工具集 | 
base64
import { Base64 } from 'amos-tool';
// or import Base64 from 'amos-tool/lib/encrypt/_base64';
var b64 = new Base64();
  b64.encode(input);
  b64.decode(input);
md5
import { MD5 } from 'amos-tool';
// or import MD5 from 'amos-tool/lib/encrypt/_md5';
var result = MD5('value'); // 2063c1608d6e0baf80249c42e2be5804
var result = MD5('value', 'key'); // 01433efd5f16327ea4b31144572c67f6
var result = MD5('value', null, true); // 'c\xc1`\x8dn\x0b\xaf\x80$\x9cB\xe2\xbeX\x04'
var result = MD5('value', 'key', true); // '\x01C>\xfd_\x162~\xa4\xb3\x11DW,g\xf6'
des
注意,加密解密时,第一个
秘钥不能为空
DES.DesCore.encode(data, firstKey, secondKey, thirdKey)
DES.DesCore.decode(data, firstKey, secondKey, thirdKey)
DES.encode(data, secretKey);
DES.decode(data, secretKey);
- example
import { DES } from 'amos-tool';
// or import DES from 'amos-tool/lib/encrypt/des';
const desCore = DES.DesCore;
desCore.encode('123456', 'a'); // 484FD6D18A5501370873DB5F557A23F9
desCore.encode('123456', 'a', 'b'); // 953AFFF48E49E4B94D8B74AABB6905E5
desCore.encode('123456', 'a', 'b', 'c'); // 7C49B05CCBCBEECC5665732A177E624B
desCore.decode('484FD6D18A5501370873DB5F557A23F9', 'a'); // 123456
desCore.decode('953AFFF48E49E4B94D8B74AABB6905E5', 'a', 'b'); // 123456
desCore.decode('7C49B05CCBCBEECC5665732A177E624B', 'a', 'b', 'c'); // 123456
DES.encode('123456', 'a'); // 484FD6D18A5501370873DB5F557A23F9
DES.encode('123456', 'a,b'); // 953AFFF48E49E4B94D8B74AABB6905E5
DES.encode('123456', 'a,b,c'); // 7C49B05CCBCBEECC5665732A177E624B
DES.decode('484FD6D18A5501370873DB5F557A23F9', 'a'); // 123456
DES.decode('953AFFF48E49E4B94D8B74AABB6905E5', 'a,b'); // 123456
DES.decode('7C49B05CCBCBEECC5665732A177E624B', 'a,b,c'); // 123456
注意:
secretKey 'a,b,c' 与 a, b,c 不同,识别空格。 支持3个秘钥,采用 , 分割
同时,DES.DesCore 第一个 key 值不可以为 空('', undefined, null)
browser
  Browser.isFirefox();
  Browser.isIE();
  Browser.isEdge();
  Browser.isChrome();
  Browser.isSafari();
deepCopy
import { deepCopy } from 'amos-tool';
deepCopy(source);
import deepCopy, { eq } from 'amos-tool/lib/_deepCopy';
eq(value, other)
deepEqual
deepEqual(valA, valB);
fastDeepEqual
fastDeepEqual(valA, valB);
parseText
/**
 * 解析数据
 * @param {string} text
 * @param {object} dataObj
 * @param {string|RegExp} regexps 可选
 * @doc parseText('a/{b}/{c}/d',{a: 1, b:2}) 返回: 'a/1/2/d'
 * @doc parseText('a/b?name={name}&pwd={pwd}',{name: 'ilex', pwd:122}) 返回: 'a/b?name=ilex&pwd=123'
 */
parseText(text, dataObj, regexps);
list
  List props:
    ArrayList: var arrlist = new List.ArrayList();
    parse2string: List.parse2string(obj)
    parse2object: List.parse2object(str)
    simpleEqual: List.simpleEqual(objA, objB)
    isObject: List.isObject(obj)
  // ArrayList
  var arrlist = new List.ArrayList();
  arrlist.size(); // get size of list
  arrlist.values();// all values
  arrlist.isEmpty();// check empty
  arrlist.iterator(callBack);// iterator
  arrlist.get(index);// 取得指定下标的值
  arrlist.add(value); // add item
  arrlist.addAll(value);// add all item, value is a arrayList
  arrlist.set(index, value);// 设置值
  arrlist.remove(value);// remove item
  arrlist.removeAt(index); //  //remove item by index
  arrlist.indexOf(value); // get item index from list
  arrlist.clear(); // clear list
  arrlist.insert(index, value); // insert item in index place
  arrlist.updateValue(key, value); // use value[key] check equal
queue
  var q = new Queue;
  q.push(obj) // 入队
  q.pop();// 出队
  q.head();// 返回队列中头部(即最新添加的)的动态对象
  q.tail();// 返回队列中尾部(即最早添加的)的动态对象
  q.length();// 返回数据队列长度
  q.empty(); // 队列是否为空
  q.clear(); // 清空
uuid
  uuid(len, radix); // radix must be <= 62 , uuid(8, 2)
  uuidFast();
  uuidCompact();
  timeUUID(prefix = 'amos-timeuuid');
  longTimeUUID(prefix = 'longtime');
  otherUUID(tpl = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'); // 同 uuidCompact,无 '-'
browserSupport
- apis
  simpleuse:
    defaultConfig: ['firefox/51.0', 'chrome/56']
    browserSupport();
    browserSupport('firefox/51.0');
    browserSupport(['firefox/51.0', 'chrome/56']);
  withMatchs:
    muitlConfig: ['firefox/', 'chrome/'];
    browserSupport(null, {
      'firefox/': {limit: consts.GREATER_EQUAL, version: 51},
      'chrome/': {limit: consts.GREATER_EQUAL, version: 56}
    });
    browserSupport('firefox/', {limit: consts.GREATER_EQUAL, version: 51});
    browserSupport(['firefox/', 'chrome/'], {
      'firefox/': {limit: consts.GREATER_EQUAL, version: 51},
      'chrome/': {limit: consts.GREATER_EQUAL, version: 56}
    });
  consts:
    GREATER: 1, // 大于
    EQUAL: 2, // 等于
    LESS: 3, // 小于
    GREATER_EQUAL: 4, // 大于等于
    LESS_EQUAL: 5 // 小于等于
- demo
// 基本使用
const result = browserSupport();
const paramsList = ['firefox/', 'chrome/', 'ie'];
const limit = {
  'firefox/': { limit: consts.GREATER_EQUAL, version: 50 },
  'chrome/': { limit: consts.GREATER_EQUAL, version: 55 },
  'ie': { limit: consts.GREATER_EQUAL, version: 6 }
};
// 自定义使用 (注意适配ie时 写法)
const result2 = browserSupport(paramsList, limit);
log
  window.LogConfig
  window.LogConfig.isDebug
  Log.trace()
  Log.debug()
  Log.info()
  Log.warn()
  Log.error()
  Log.fatal()
  // 展示 pkg 信息,不受 LogConfig 配置影响
  Log.pkgInfo(name, version)
store
`default function list`
  // 所有的cookie数据,均采用 escape/unescape 进行转码、解码
  encrypt(str) // 加密
  decrypt(str) // 解密
  setCookieByDays(name, value, days)
  getAllCookies() // 获取所有的cookie,同时每个key对应的value,均执行了 JSON.parse(value)
  setCookieByHour(name, value, hour)
  getCookieByName(name)
  removeCookieByName(name)
  clearAllCookie()
`localStorage`
  const ls = Store.lsTool;
    ls.read(key)
    ls.write(key, data)
    ls.each(fn)
    ls.remove(key)
    ls.clearAll()
  `sessionStorage`
    const session = Store.session;
    session.read(key)
    session.write(key, data)
    session.each(fn)
    session.remove(key)
    session.clearAll()
locationParam
  parse(paramString):
    `if paramString is undefined, paramString=window.location.search`
    `return all params Key Pair object`
  paramSearch(name, target):
    `if target is undefined, default window.location.search`
    `and if name is undefined too `
    `return keyValueObjec; else if name not empty return value;`
  getLocationParams():
    `get all locationParams, and return a key-value object`
  getLocationParamByName(name):
    `get param value by name, and return value or null`
  getParameter(url, name):
    `get target url Parameter by name, and return value or '' `
  extractParam(url, name): `解析指定 url 中的参数,返回指定 name 的参数`
  extractParams(url): `解析指定 url 中的参数,参数对象,如果 url 为undefined,则默认采用 window.location.href`
  `LocationSearch` LocationParam.LocationSearch
    `other search tool`
    private: _keyValuePairs
    public:
      init():
        `init this tool,set private property _keyValuePairs and return a LocationSearch`
      getValue(key):
        `return target value`
      getParameters():
        `return all param value`
array2tree
import { array2tree } from 'amos-tool';
const data = [{
  value: 'a',
  children: [{
    value: 'b',
    children: [{
      value: 'c'
    }, {
      value: 'd',
    }]
  }],
}];
const values = ['a', 'b', 'c'];
const result = array2tree(
  data, (item, level) => item.value === values[level]
);
console.log(result);
// [
//   { value: 'a', children: [...] },
//   { value: 'b', children: [...] },
//   { value: 'c', children: [...] }
// ]
tableFilter
  getChildrenlength(children)
  flatToHierarchy(arr)
  filterParentPosition(arr)
  isInclude(smallArray, bigArray)
 /**
  * 过滤数据
  *
  * @param {Array} vals 数据集合
  * @param {any} treeData tree数据
  * @returns
  */
  filterAllCheckedData(vals, treeData)
  /**
   * 递归
   *
   * @param {any} children
   * @param {any} cb
   */
  recursive(children, cb)
pwdPolicy
  /**
  * 普通密码生成策略
  * @param {string} password
  * @return {object} { password, secretKey }
  */
  normalPolicy(password)
  /**
  * 普通密码生成策略
  * @param {string} password 密码
  * @param {string} secretKey 秘钥
  * @return {object} { password, secretKey }
  */
  advancePolicy(password, secretKey)
  /**
   * 采用MD5生成密码 (不可逆)
   * @param {string} password
   * @param {string} secretKey
   */
  useMd5Policy(password, secretKey)
omit
  const ilex = {name: 'ilex', age: 18};
  const copy = omit(ilex, ['']); // {name: 'ilex', age: 18};
  const copy = omit(ilex, ['age']); // {name: 'ilex'}
  const copy = omit(ilex, ['name', 'age']); // {}
pick
  const ilex = {name: 'ilex', age: 18};
  const copy = pick(ilex, ['']); // {};
  const copy = pick(ilex, ['age']); // {age: 18}
  const copy = pick(ilex, ['name', 'age']); // {name: 'ilex', age: 18}
utils
  isString(obj);
  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  `If you want to judge object and judge array, you need to judge array first`
  isArray(obj);
  // Is a given variable an object?
  isObject(obj);
  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  isEmpty(objOrArray);
  // Is a given value equal to null?
  isNull(obj);
  // Is a given variable undefined?
  isUndefined(obj);
  // Is json
  isJson(obj);
  // is image src,支持的格式(jpe?g|png|gif|bmp|ico|tga) 及其 base64 格式
  isImageSrc(url);
  /**
   * 将数字部分内容转化为 *
   * @param {Number} number 目标 Number
   * @param {Number} start 起始位置
   * @param {Number} len 转换位数
   * @param {String} sign 替换的字符
   */
  encodeNumber(number, start = 3, len = 4, sign = '*');
  /**
    * some
    * some 为数组中的每一个元素执行一次 callback 函数,直到找到一个使得 callback 返回一个“真值”
    * @param {Array} arr
    * @param {function} fun
    */
  some(arr, fun /*, thisArg */ );
  //
  every(arr, callbackfn, thisArg);
  //
  reduce(arr, callback /*, initialValue*/);
  mergeAll(targetAndSources, overwrite);
  merge(target, source, overwrite);
  clone(source);
xss
import htmlEncode from 'amos-tool/lib/xss/htmlEncode';
import implementEncode from 'amos-tool/lib/xss/implementEncode';
htmlEncode('<'); // <
htmlEncode('>'); // >
htmlEncode('\''); // '
htmlEncode('\"'); // "
...
implementEncode('<script language=text/javascript>alert(document.cookie);</script>');
implementEncode('</script>');
implementEncode(' eval(abc);');
implementEncode('<img src="" onerror="alert(document.cookie);"></img>');
...
strUtils
  toCapitalStr(obj);
  // 驼峰化, 仅支持首字母大写、或者采用中杠连接的两个字母首字母大写
  // 如果要支持其它输入,将正则改为: /(-|(\s+)|_)(\w)/g
  camelCase(obj);
  // 将中缸连接的字符串 驼峰化
  transCamel(obj);
  // 字符串首字母大写
  capFirst(objOrArray);
  // 获取字符串的hashCode码
  hashCode(obj);
  // 进制与单位处理
  dealScaleAndUnit(obj);
other
- 
cookie: 
- 
isNode isNode(); 
- 
objectAssign: objectAssign(target, source);
- 
parseJson: parseJson(data) 
- 
stringify: stringify(json) 
- 
supportWs: supportWs() 
- 
trim: trim(str) 
- 
arrayFilter: 
- 
merged: merged(args): combine object property 
- 
objectPath @see doc/objectPath.md 
- 
random random(len) random.randomInt(min, max) 
extra
- pathToTree
import pathToTree from 'amos-tool/lib/extra/pathToTree';
const arr = [
  'main/lib',
  'console/tt/design1',
  'console/mm/vizlib'
];
const mapper = {
  main: 'RootView',
  console: 'ConsoleView'
};
var result1 = pathToTree(arr, {
  pathKey: 'path',
  childrenKey: 'childRoutes',
  processor(item, wantedNode){
    if (mapper[wantedNode]){
      item.component = mapper[wantedNode];
    }
  }
});
dom
- canvas2img
saveAsImage(canvas/canvasElement/, width, height, type) saveAsPNG(canvas, width, height) saveAsGIF(canvas, width, height) saveAsBMP(canvas, width, height) convert2Image(canvas, width, height, type) convert2data(canvas, type, width, height) convert2Blob
/**
  * @param {Canvas} canvas
  * @param {function} fn (blob) => {}
  * @param {Object} options {
  *  type: '', // 图片类型 默认 'image/png',其它类型详见MIME手册
  *  width: number, // 宽
  *  height: number, // 高
  *  encoderOptions: 0-1 // 图片质量
  * }
  */
convert2Blob(canvas, fn, options)
convert2PNG(canvas, width, height) convert2JPEG(canvas, width, height) convert2GIF(canvas, width, height) convert2BMP(canvas, width, height)
changelog
- 
v1.6.13 *fix color Log
- 
v1.6.3 *fix Log
- 
v1.6.1 *fix saver
- 
v1.4.1 *addpathToRoutes
- 
v1.4.0 *addpathToTreeto calc react router path
- 
v1.3.21 *modify colorUtil
- 
v1.3.19 *modify colorUtil*modifyutils#getFileExtension*modifyindex.d.ts
- 
v1.3.14 *modify cookie encode method+browser/indexDB
- 
v1.3.13 +htmlEncode+implementEncode