Skip to main content

Other

Code

import { isArray } from "lodash";

/**
* 数据格式化 [ [{}], [{}], [{}] ] ===> [ {} ]
* @param arr 需要处理的数组
*/
export const convertArray = (arr: any[]) => {
if (isArray(arr[0])) {
return [].concat(...arr);
}
return arr;
};

// compose
// https://github.com/reduxjs/redux/blob/master/src/compose.ts
export const compose = (...fn: Function[]) => {
if (fn.length === 0) {
return <T>(arg: T) => arg;
}

if (fn.length === 1) {
return fn[0];
}

return fn.reduce(
(a, b) =>
(...args: any) =>
a(b(...args))
);
};

/**
* sleep
* @param time number
* @returns
*/
export const sleep = (time: number) =>
new Promise((resolve) => setTimeout(resolve, time));

// ------ REG --------
// match 不包含 AB 的字符
export const matchStr = (str: string, left: string, right: string) => {
const pattern = new RegExp(`(?<=${left}).*?(?=${right})`);
return str.match(pattern);
};

/**
* 首字母大写
* @param param0 string
* @returns String
*/
export const firstUpperCase = ([first, ...other]: any) => {
return first.toLocaleUpperCase() + other.join("");
};

/**
* 范围随机数
* @param min 最小
* @param max 最大
* @returns number
*/

export const randomRange = (min: number, max: number): number =>
Math.floor(Math.random() * (max - min + 1) + min);

Test

import { expect } from "chai";
import {
convertArray,
firstUpperCase,
matchStr,
sleep,
compose,
randomRange,
} from "../src/index";

describe("convertArray", function () {
it("二维数组转换为一维数组 [ [{a: 1}], [{a: 2}] to [{a: 1}, {a: 2}]", function () {
const result = convertArray([[{ a: 1 }], [{ a: 2 }]]);

expect([{ a: 1 }, { a: 2 }]).to.deep.equal(result);
});
it("二维数组转换为一维数组 [{a:1}] to [{a:1}]", function () {
const result = convertArray([{ a: 1 }]);

expect([{ a: 1 }]).to.deep.equal(result);
});
});

describe("firstUpperCase", function () {
it("首字母大写 xiaotian to Xiaotian", function () {
const result = firstUpperCase("xiaotian");

expect("Xiaotian").to.equal(result);
});
});

describe("matchStr", function () {
it(" match 不包含 AB 的字符 --aaaaaaaa!! to aaaaaaaa", function () {
const result = matchStr("--aaaaaaaa!!", "--", "!!");
const resultStr = result?.length ? result[0] : "";

expect("aaaaaaaa").to.equal(resultStr);
});
});

describe("sleep", function () {
it("sleep Xms", async function () {
console.log("sleep", Date.now());
const result = await sleep(1);
console.log("sleep", Date.now());

// TODO: 暂时不知道咋写...
expect("sleep").to.equal("sleep");
});
});

describe("compose", function () {
it("compose 0 to 3", function () {
const add = (x: number) => ++x;
const result = compose(add, add, add)(0);

expect(3).to.equal(result);
});

it("compose 0 to 1", function () {
const add = (x: number) => ++x;
const result = compose(add)(0);

expect(1).to.equal(result);
});

it("compose 0 to 0", function () {
const result = compose()(0);

expect(0).to.equal(result);
});
});

describe("randomRange", () => {
it("random 1 - 5", () => {
const result = randomRange(1, 5);
expect([1, 2, 3, 4, 5]).to.include(result);
});
});