@alrale/common-lib
v1.0.75
Published
common functions
Downloads
223
Readme
@alrale/common-lib
- common functions
- small tool
Installing
$ yarn add @alrale/common-lib
Functions
- appendjs
- array
- arrayToObject
- arrayMove
- arrayMoveMutate
- arrayRange
- browser
- isSafari
- isChrome
- isFirefox
- isOpera
- isEdge
- isIE
- byte
- format
- console
- skipAll
- skip
- skipAllBy
- skipBy
- collectAll
- collect
- onlyAll
- only
- color
- hexTransparency
- date
- formatTs
- deep.clone
- deepClone
- deepOClone
- document
- copyValue
- disableBehavior
- scrollToTop
- env
- isBrowser
- UA
- isIE
- isIE9
- isEdge
- isAndroid
- isIos
- isChrome
- isFF
- each
- each
- has
- keys
- values
- filter
- json
- parseJSON
- parseJsonDeep
- number
- randomInt
- randomDistinctIntArray
- randomDistinctRangeArray
- prefixZero
- isNumber
- isInt
- isFloat
- object
- sortMapByKey
- mapToVArray
- objectToArray
- makeMap
- isEmpty
- parse.query
- parseQuery
- decodeUrlSearch
- query.to.string
- queue
- ArrayQueue
- LinkedQueue
- regular
- schedule
- execInterval
- autoStopInterval
- sleep
- sleep
- sleepSync
- store
- setStore
- getStore
- setOStore
- getOStore
- removeStore
- string
- randomString
- nameDesensitization
- desensitization
- positionOfStringIndexes
- uniqueId
- guid
- uuid
- guid2
- uuid2
- stringExtension
- utf8ToBase64
- base64ToUtf8
- time.axis
- dateDiff
- week
- to.simplified.chinese
- type.is
- typeIs
- isNumberExt
- isBoolean
- isSymbol
- isUndefined
- isNull
- isFunction
- isDate
- isArray
- isObject
- isMap
- isSet
- isRegExp
- isError
- window
- globalStore
- getGlobal
- setGlobal
- removeGlobalItem
- client
- desktopNotification
- Complex
- targetConversionIntoList
- adjustProgress
appendjs
动态加载 script
appendJs("http://code.jquery.com/jquery-migrate-1.2.1.min.js", function () {
console.log("jquery success");
});
array
arrayToObject
const arr = [
{ id: 1, test: 123 },
{ id: 2, test: 345 },
];
const obj = arrayToObject("id", arr); // => { '1': { id: 1, test: 123 }, '2': { id: 2, test: 345 } }
arrayMove 数组位移
Learn from array-move
const input = ["a", "b", "c"];
const array1 = arrayMove(input, 1, 2);
expect(array1).toEqual(["a", "c", "b"]);
const array2 = arrayMove(input, -1, 0);
expect(array2).toEqual(["c", "a", "b"]);
const array3 = arrayMove(input, -2, -3);
expect(array3).toEqual(["b", "a", "c"]);
arrayMoveMutate 引用数组位移,性能优化
const input1 = ["a", "b", "c"];
arrayMoveMutate(input1, 1, 2);
expect(input1).toEqual(["a", "c", "b"]);
const input2 = ["a", "b", "c"];
arrayMoveMutate(input2, -1, 0);
expect(input2).toEqual(["c", "a", "b"]);
const input3 = ["a", "b", "c"];
arrayMoveMutate(input3, -2, -3);
expect(input3).toEqual(["b", "a", "c"]);
arrayRange 序列生成器
const arr1 = arrayRange(0, 5, 2);
expect(arr1).toEqual([0, 2, 4]);
const arr2 = arrayRange(1, 5, 2);
expect(arr2).toEqual([1, 3, 5]);
browser
getKernel 获取浏览器内核
const kernel = getKernel(); // => 'IE7'|'IE8'|'IE9'|'IE10'|'IE11'|'IE'|'Opera'|'Edge'|'FF'|'Safari'|'Chrome'|'None'
getKernelVersion 获取浏览器内核
const kernelVersion = getKernelVersion(); // => 'chrome 92.0.4515.131'
const kernel = getKernelVersion("name"); // => 'chrome'
const version = getKernelVersion("version"); // => '92.0.4515.131'
getOs 获取操作系统
const os = getOs(); // => 'Windows' | 'Mac' | 'iPhone' | 'iPod' | 'iPad' | 'Android' | 'Linux' | 'Unknown'
isSafari, isChrome, isFirefox, isOpera, isEdge, isIE
const {
isSafari,
isChrome,
isFirefox,
isOpera,
isEdge,
isIE,
} = require("@alrale/common-lib");
isSafari; // => boolean
isChrome; // => boolean
isFirefox; // => boolean
isOpera; // => boolean
isEdge; // => boolean
isIE; // => boolean
byte
format 字节转换
const { byte } = require('@alrale/common-lib');
// from byte to kb
const b2kb = byte.format(2048).Byte.toKB(); // => 2
// from mb to bit
byte.format(...).MB.toBit()
// from ... to ...
console
日志过滤器
const { log } = require("@alrale/common-lib");
// type LevelType = 'info' | 'log' | 'debug' | 'warn' | 'error';
skipAll 全部禁用
log.skipAll();
console.log("---这个信息不会输出----");
skip level 级别禁用
log.skip(["log"]);
console.log("---这个信息不会输出---");
console.info("---这个信息会输出---");
skipAllBy 条件禁用
log.skipAllBy({ startWitch: "[d" });
console.log("这个信息会输出");
console.log("[debug]这个信息不输出-> ", 123);
skipBy level 级别禁用|条件过滤
log.skipBy(["log"], { endWitch: "foo" });
console.log("[debug]这个会log1-> ", 123);
console.log("这个信息不会输出foo");
console.log("[debug]这个会log2-> ", 123);
collectAll 收集
log.collectAll({
prefix: "1",
callback: (args) => {
console.info("----->", args);
},
});
console.log("[debug]123-> ", 123);
console.log("1这个是", { a: 1 }, "测试");
collect level 级别收集|条件过滤
log.collect("log", {
prefix: "1",
callback: (args) => {
console.info("收集------>", args);
},
});
console.log("[debug]不会被收集-> ", 123);
console.log("这个会被收集", { a: 1 }, "测试");
onlyAll 只展示[prefix]相关
log.onlyAll({ startWitch: "[debug]" });
console.log("[debug]这个会输出-> ", 123);
console.log("这个不会输出");
console.info("[debug]这个也会输出-> ", true);
only level 级别只展示[prefix]相关
log.only("info", { startWitch: "[debug]" });
console.info("[debug]这个会输出-> ", 123);
console.info("测试测试");
console.log("这个也输出");
color
hexTransparency css 颜色十六进制末尾透明度对照
const hexSuffix = color.hexTransparency["50%"]; // -> '80'
// #00000080 -> gray
date
formatTs 格式化时间戳
const { date } = require("@alrale/common-lib");
// 2021年1月2日3时4分5秒 = 1609527845
const {
year, // 2021
month, // 1
day, // 2
hour, // 3
minutes, // 4
seconds, // 5
} = formatTs(1609527845);
// 2009年10月12日13时44分55秒 = 1255326295
const {
fullMonth, // '10'
fullDay, // '12'
fullHour, // '13'
fullMinutes, // '44'
fullSeconds, // '55'
} = formatTs(1255326295000);
const ymd = formatTs(1609527845).getYMD(); // => '2021-1-2 3:4:5'
const fullYmd = formatTs(1609527845).getYYYYMMDD("/", "/"); // => '2021/01/02 03/04/05'
deep.clone
deepClone, deepOClone 深复制
const { deepClone, deepOClone } = require("@alrale/common-lib");
// object -> string -> object
const foo1 = { a: 1, b: 2 };
const foo_copy1 = deepClone(foo1); // foo_copy1 !== foo1
// object deep clone -> other object
const foo2 = [{ a: 1, b: 2 }];
const foo_copy2 = deepOClone(foo2); // foo_copy2 !== foo2
document
copyValue 复制功能
const { copyValue } = require('@alrale/common-lib');
copyValue(value: string /**浏览器需要复制的文本 */): void;
disableBehavior 禁止浏览器行为 选择|复制|拖拽|...
const { disableBehavior } = require('@alrale/common-lib');
disableBehavior(['contextmenu', 'selectstart', 'copy']): void;
scrollToTop 滑滚动页面到顶部
const { scrollToTop } = require('@alrale/common-lib');
scrollToTop(): void;
env
客户端环境
const {
isBrowser, // 判断是否是浏览器访问 => boolean
UA, // userAgent => any
isIE, // => boolean
isIE9, // => boolean
isEdge, // => boolean
isAndroid, // => boolean
isIos, // => boolean
isChrome, // => boolean
isFF, // => boolean
} = require("@alrale/common-lib");
each
const { each } = require("@alrale/common-lib");
each(object | array, function(key, value, done) { ... })
has 判断对象或数组是否包含 key
const { has } = require("@alrale/common-lib");
has({ a: 1 }, "a"); // => true
has([1, 2], 0); // => true
keys 获取对象或数组 keys 列表
const { keys } = require("@alrale/common-lib");
keys({ a: 1, b: 2, d: "abd" }); // => ['a', 'b', 'd']
values 获取对象或数组值
const { values } = require("@alrale/common-lib");
values({ a: 1, b: 2, d: "abd" }); // => [1, 2, 'abd']
filter
json
parseJSON 反序列化
const { parseJSON } = require("@alrale/common-lib");
const longStr =
'{"errorCode":100,"errorMsg":null,"data":[{"cityCode":"110100","cityName":"北京市","mallAreaList":[{"areaCode":"110101","areaName":"东城区"},{"areaCode":"110102","areaName":"西城区"},{"areaCode":"110105","areaName":"朝阳区"},{"areaCode":"110106","areaName":"丰台区"},{"areaCode":"110107","areaName":"石景山区"},{"areaCode":"110108","areaName":"海淀区"},{"areaCode":"110109","areaName":"门头沟区"},{"areaCode":"110111","areaName":"房山区"},{"areaCode":"110112","areaName":"通州区"},{"areaCode":"110113","areaName":"顺义区"},{"areaCode":"110114","areaName":"昌平区"},{"areaCode":"110115","areaName":"大兴区"},{"areaCode":"110116","areaName":"怀柔区"},{"areaCode":"110117","areaName":"平谷区"}]},{"cityCode":"110200","cityName":"北京市辖县","mallAreaList":[{"areaCode":"110228","areaName":"密云县"},{"areaCode":"110229","areaName":"延庆县"}]}]}';
const json = parseJSON(longStr);
parseJsonDeep 反序列化 [深度]
const { parseJsonDeep } = require("@alrale/common-lib");
const mockData = {
one: JSON.stringify({
two: JSON.stringify({
three: JSON.stringify({
four: JSON.stringify({
time: "08:20",
}),
}),
}),
}),
};
const json = parseJsonDeep(mockData);
number
const {
randomInt,
randomDistinctIntArray,
randomDistinctRangeArray,
isNumber,
isFloat,
prefixZero,
isInt,
} = require("@alrale/common-lib");
randomInt 随机区间整数
const num = randomInt(); // default max = 10
num <= 10; // => true
num >= 0; // => true
const num1 = randomInt(10, 5);
num <= 10; // => true
num >= 5; // => true
randomDistinctIntArray 随机获取整数列表
const list = randomDistinctIntArray(10);
list.includes(6); // => true
// 默认[0]
const defaultList = randomDistinctIntArray();
// defaultList equal [0]
randomDistinctRangeArray
随机区间唯一整数的列表
随机获取固定长度 len 的数组
最小出现值 fromMin
最大出现值 toMax
// 默认[0~10]
const defaultList = randomDistinctRangeArray();
expect(defaultList.length).toBe(1);
const list = randomDistinctRangeArray(10, 5, 6);
for (let i = 0; i < list.length; i++) {
const item = list[i];
expect([5, 6, 7, 8, 9, 10].includes(item)).toBe(true);
if (i === list.length - 1) done();
}
prefixZero 整数前置补零
prefixZero(2); // => '02'
prefixZero(20); // => '20'
prefixZero(20, 3); // => '020'
prefixZero(); // => ''
prefixZero(2.21); // => ''
prefixZero(true); // => ''
prefixZero(20, 6); // => '000020'
prefixZero(-20); // => ''
isNumber 判断数字类型,(包含字符串类型数字)
isNumber("one"); // => false
isNumber("2"); // => true
isNumber(() => {}); // => false
isNumber(1.23); // => true
isNumber(true); // => false
isInt 严格校验正负正数
isInt(122); // => true
isInt(-122); // => true
isInt(true); // => false
isInt("032"); // => true
isInt([]); // => false
isFloat 判断是否位 float 格式
isFloat("1"); // => false
isFloat("1.2"); // => true
isFloat([1.1, 2.2]); // => false
isFloat(2.334); // => true
object
const {
sortMapByKey,
mapToVArray,
objectToArray,
makeMap,
} = require("@alrale/common-lib");
sortMapByKey 对象 key 排序
const object = { 12: { a: 1 }, 4: 4, 7: true, 1: "haha" };
const resObj = sortMapByKey(object, false); // resObj[12] => { a: 1 }
const map = new Map();
map.set(12, { a: 1 }).set(4, 4).set(7, true).set(1, "haha");
const resMap = sortMapByKey(map); // resMap.get(1) => 'haha'
mapToVArray Map to value 数组
const map = new Map();
map.set("a", 1).set("b", null).set("c", [1, 2]).set("d", true);
const arr = mapToVArray(map); // arr.includes(true) === true
objectToArray 对象 to 对象数组
const obj = { a: 1, b: null, c: [1, 2], d: { val: "haha" } };
const objArr = objectToArray(obj); // objArr[0].a === 1
const map = new Map();
map.set("a", 1).set("b", null).set("c", [1, 2]).set("d", true);
const mapArr = objectToArray(map); // mapArr.length === map.size
makeMap Make a map and return a function for checking if a key
const acceptValue = makeMap("input,textarea,option,select,progress");
const acceptValue2 = makeMap("input,textarea,option,select,progress", true);
const bool = acceptValue("input"); // => true
const bool2 = acceptValue2("INPUT"); // => true
isEmpty 判断 Object 是否是空对象
object.isEmpty({}); // => true
object.isEmpty({ alrale: "common-lib" }); // => false
object.isEmpty([1, 2, 3]); // => false
parse.query
const { parseQuery, decodeUrlSearch } = require("@alrale/common-lib");
parseQuery 格式化 url 参数
const url = "https://www.gaodeditu.com?areaName=%E5%8C%97%E4%BA%AC&xml=test";
const params = parseQuery(url); // => { areaName: "北京", xml: "test" }
decodeUrlSearch window.location.search 解码
const search = "?areaName=%E5%8C%97%E4%BA%AC&xml=test=";
const params = decodeUrlSearch(search); // => { areaName: "北京", xml: "test=" }
query.to.string
object -> ?xxx=xxx&xxx=xxx
const { queryToString } = require("@alrale/common-lib");
const params = queryToString({ a: 1, b: "foo", c: "汉" }); // => ?a=1&b=foo&c=%E6%B1%89
queue
const { ArrayQueue, LinkedQueue } = require("@alrale/common-lib");
ArrayQueue 集合队列
const queue = new ArrayQueue();
const pop = queue.pop();
expect(pop).toBeUndefined();
queue.push({ a: 1 });
queue.size(); // => 1
queue.getFront(); // => { a: 1 }
LinkedQueue 链表队列
const myQueue = new LinkedQueue();
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
myQueue.push(4);
const str1 = myQueue.toString();
str1.trim(); // => '1 2 3 4'
const pop = myQueue.pop();
pop.ele; // => 1
const str2 = myQueue.toString();
str2.trim(); // => '2 3 4'
regular
const { regular } = require("@alrale/common-lib");
const {
InternetURLReg, // Url
IDNumberReg, // 身份证号(15位或18位数字)
EmailReg, // 邮箱
ChineseReg, // 中文
IntegerReg, // 整数
NotNegativeFloatReg, // 非负浮点数(正浮点数 + 0)
NotPositiveFloatReg, // 非正浮点数(负浮点数 + 0)
} = regular;
// Url
const baidu = "http://www.baidu.com";
const baidus = "https://www.baidu.com";
const ftp = "ftp://192.168.2.1/dir";
InternetURLReg.test(baidu); // => true
InternetURLReg.test(baidus); // => true
InternetURLReg.test(ftp); // => true
// 身份证
const idList = ["130928198905281793", "130532197901235712"];
for (let i = 0; i < idList.length; i++) {
const number = idList[i];
const bool = IDNumberReg.test(number); // => true
}
// 邮箱
const mailList = ["[email protected]", "[email protected]"];
for (let i = 0; i < mailList.length; i++) {
const mail = mailList[i];
const bool = EmailReg.test(mail); // => true
}
// 中文
ChineseReg.test("中文"); // => true
ChineseReg.test("1"); // => true
ChineseReg.test([""]); // => false
// 整数
IntegerReg.test(12); // => true
IntegerReg.test(-12); // => true
IntegerReg.test(12.32); // => false
IntegerReg.test(true); // => false
// 非负浮点数(正浮点数 + 0)
NotNegativeFloatReg.test(12); // => true
NotNegativeFloatReg.test(-12); // => false
NotNegativeFloatReg.test(12.32); // => true
NotNegativeFloatReg.test([]); // => false
// 非正浮点数(负浮点数 + 0)
NotPositiveFloatReg.test(12); // => false
NotPositiveFloatReg.test(-12); // => true
schedule
const { execInterval, autoStopInterval } = require("@alrale/common-lib");
execInterval 定时器
let count = 0;
const clearInterval = execInterval(500, () => (count += 1));
setTimeout(() => {
expect(count).toBeGreaterThan(1);
expect(count).toBe(2);
clearInterval();
done();
}, 1100);
autoStopInterval 自动结束定时器
let count = 0;
setTimeout(() => {
expect(count).toBe(2);
done();
}, 1100);
autoStopInterval(500, 1200, (status) => {
count += 1;
if (count === 3) expect(status).toBe("done");
});
let count = 0;
let clearFunc = null;
setTimeout(() => {
clearFunc();
expect(count).toBe(4);
done();
}, 2 * 1000 + 100);
clearFunc = await Schedule.autoStopInterval(
500,
4 * 1000 + 100,
() => (count += 1)
);
sleep
const { sleep, sleepSync } = require("@alrale/common-lib");
sleep.sleep async
async () => {
const _start = Date.now();
await sleepSync(1000);
const _calc = Date.now() - _start;
expect(parseInt(_calc / 1000)).toBe(1);
};
sleepSync sync
(done) => {
const _start = Date.now();
sleep(1000, () => {
const _calc = Date.now() - _start;
expect(parseInt(_calc / 1000)).toBe(1);
done();
});
});
}
store
const {
setStore,
getStore,
setOStore,
getOStore,
removeStore,
} = require("@alrale/common-lib");
setStore set session | local store 、getStore get session | local store
// session
const s_key = "session_key";
setStore(s_key, "test session");
getStore(s_key); // => 'test session'
// local
const l_key = "local_key";
setStore(l_key, "test local", "local");
getStore(l_key, "local"); // => test local
// boolean -> string
const b_s_key = "b_s_key";
setStore(b_s_key, true);
getStore(b_s_key); // => typeof bool === 'string'
setOStore set object、getOStore get object
// object session
const o_s_key = "o_s_key";
setOStore(o_s_key, { foo: 123 });
getOStore(o_s_key); // => 123
// object local"
const o_l_key = "o_l_key";
setOStore(o_l_key, { foo: 456 }, "local");
getOStore(o_l_key, "local"); // => 456
// boolean -> boolean
const o_b_s_key = "o_b_s_key";
setOStore(o_b_s_key, true);
const o_bool = getOStore(o_b_s_key); // => typeof o_bool === 'boolean'
removeStore remove store
removeStore(key, [level]): void
string
const {
randomString,
nameDesensitization,
desensitization,
positionOfStringIndexes,
uniqueId,
guid,
uuid,
guid2,
uuid2,
stringExtension,
} = require("@alrale/common-lib");
randomString 随机字符串
const defaultStr = randomString(); // => defaultStr.length === 32
const str = randomString(16); // => str.length === 16
nameDesensitization 名字脱敏
const name = nameDesensitization("张三丰"); // => '张*丰'
desensitization 字符串脱敏
const str = desensitization("asdfg", 1, 3); // => 'a**fg'
positionOfStringIndexes 字符串索引位置列表
const str = "asdfasdfasdfasdfasdfasdf";
const target = "asdf";
const list = positionOfStringIndexes(str, target);
expect(list).toEqual([0, 4, 8, 12, 16, 20]);
const target2 = "123";
const list2 = positionOfStringIndexes(str, target2);
expect(list2).toEqual([]);
uniqueId 唯一(24 位长度)Id
// 1w次随机,不重复
let count = 10000;
const cache = {};
const repetition = [];
while (count) {
const unId = uniqueId();
if (cache[unId]) repetition.push(unId);
cache[unId] = true;
count--;
}
expect(repetition).toEqual([]);
guid、uuid、guid2、uuid2 指定长度和基数
const _uuid = uuid();
const _guid = guid();
const _uuid2 = uuid2(16, 16);
const _guid2 = guid2();
const temp = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
expect(_uuid2).toHaveLength(16);
expect(_uuid).toHaveLength(temp.length);
expect(_guid).toHaveLength(temp.length);
expect(_guid2).toHaveLength(36);
stringExtension 字符串后缀获取、判断
const str1 = stringExtension("flower.png", ".");
expect(str1).toBe("png");
const bool = stringExtension("avatar.jpg", ".", ["png", "jpg"]);
expect(bool).toBe(true);
const str2 = stringExtension("[email protected]", "@");
expect(str2).toBe("gmail.com");
const null1 = stringExtension("null.png");
expect(null1).toBe(false);
utf8ToBase64 utf8 转 base64
const base64Str = utf8ToBase64("@alrale/common-lib");
expect(base64Str).toBe("QGFscmFsZS9jb21tb24tbGli");
base64ToUtf8 base64 解码 utf8
const utf8Str = base64ToUtf8("QGFscmFsZS9jb21tb24tbGli");
expect(utf8Str).toBe("@alrale/common-lib");
time.axis
const { dateDiff, week } = require("@alrale/common-lib");
dateDiff 时间戳显示为多少分钟前,多少天前的处理
/**
* 时间戳显示为多少分钟前,多少天前的处理
* eg.
* console.log(dateDiff(1411111111111)); // 2014年09月19日
* console.log(dateDiff(1481111111111)); // 9月前
* console.log(dateDiff(1499911111111)); // 2月前
* console.log(dateDiff(1503211111111)); // 3周前
* console.log(dateDiff(1505283100802)); // 1分钟前
*/
const diff = dateDiff(1605168177);
expect(diff).toBe("1天前");
const diff = dateDiff(Date.now());
expect(diff).toBe("刚刚");
week
const day = week(7); // => '周日'
to.simplified.chinese
const { toSimplifiedChinese } = require("@alrale/common-lib");
const han = toSimplifiedChinese(12345);
expect(han).toBe("一万二千三百四十五");
typeIs
const { typeIs } = require("@alrale/common-lib");
// 'string'|'number'|'boolean'|'symbol'|'undefined'|'null'|'function'|'date'|'array'|'object'|'map' |'set'|'regexp'|'error'|'document'|'window'
const arr = typeIs([]); // => 'array'
const arr_2 = typeIs(new Array()); // => array
is... 类型判断
const {
isNumberExt,
isBoolean,
isSymbol,
isUndefined,
isNull,
isFunction,
isDate,
isArray,
isObject,
isMap,
isSet,
isRegExp,
isError,
} = require("@alrale/common-lib");
isBoolean(false); // => true
...
window
globalStore 获取全局对象
getGlobal get 全局对象
setGlobal set 全局对象
removeGlobalItem 删除 对象数据
const {
globalStore,
getGlobal,
setGlobal,
removeGlobalItem,
} = require("@alrale/common-lib");
const keyObj = "key";
const bool = setGlobal(keyObj, { value: "hehe" });
expect(bool).toBe(true);
const getObj = getGlobal(keyObj);
expect(getObj.value).toBe("hehe");
const rmBool = removeGlobalItem(keyObj);
expect(rmBool).toBe(true);
const hasObj = getGlobal(keyObj);
expect(hasObj).toBeUndefined();
client
desktopNotification 桌面通知
const { client } = require("@alrale/common-lib");
desktopNotification(
"@alrale/common-lib",
{
body: "您正在使用自定义组件库",
},
{
onclick(e) {
e.target.close();
window.focus();
},
}
);
Complex
targetConversionIntoList 目标转换成列表
const { Complex } = require("@alrale/common-lib");
it("targetConversionIntoList", () => {
const target = {
name: "张三",
age: 18,
hight: 180,
};
const list = Complex.targetConversionIntoList(target, {
name: "姓名",
age: "年龄",
hight: "身高",
});
const arr = [
{ label: "姓名", value: "张三" },
{ label: "年龄", value: 18 },
{ label: "身高", value: 180 },
];
expect(list).toEqual(arr);
});
adjustProgress 进度映射
const { Complex } = require("@alrale/common-lib");
it("adjustProgress", () => {
const mapping = [
{
real: 0,
target: 0,
},
{
real: 20,
target: 40,
},
{
real: 100,
target: 100,
},
];
const orm1 = Complex.adjustProgress(13, mapping);
expect(orm1).toBe(26);
const orm2 = Complex.adjustProgress(20, mapping);
expect(orm2).toBe(40);
const orm3 = Complex.adjustProgress(50.5, mapping);
expect(orm3).toBe(62.875);
const orm4 = Complex.adjustProgress(100, mapping);
expect(orm4).toBe(100);
const orm5 = Complex.adjustProgress(130, mapping);
expect(orm5).toBe(100);
});