jn-utils-lib
v1.0.4
Published
A collection of common utility functions for JavaScript development
Maintainers
Readme
jn-utils
一个实用的JavaScript工具函数库,提供常用的字符串、数组、对象、日期、格式化和验证等功能,以及卫星轨道计算和定时器功能。
安装
npm install jn-utils注意: 本库已内置所有必要依赖,包括satellite.js和worker-loader,无需额外安装任何依赖。
使用方法
ES6 模块导入
// 导入所有工具函数
import JnUtils from 'jn-utils';
// 或者按需导入
import { capitalize, unique, formatDate } from 'jn-utils';CommonJS 导入
const JnUtils = require('jn-utils');浏览器直接使用
<script src="dist/index.js"></script>
<script>
// 使用 JnUtils 全局对象
console.log(JnUtils.capitalize('hello'));
</script>API 文档
字符串工具 (String Utils)
capitalize(str)
首字母大写
capitalize('hello world'); // 'Hello world'camelCase(str)
转换为驼峰命名
camelCase('hello-world'); // 'helloWorld'kebabCase(str)
转换为短横线命名
kebabCase('helloWorld'); // 'hello-world'randomString(length)
生成随机字符串
randomString(8); // 'aB3xY9mK'trim(str)
去除字符串两端空格
trim(' hello '); // 'hello'maskString(str, start, end, mask)
字符串脱敏
maskString('13812345678', 3, 4); // '138****5678'truncate(str, length, suffix)
字符串截断
truncate('hello world', 5); // 'hello...'reverse(str)
字符串反转
reverse('hello'); // 'olleh'isEmptyString(str)
检查字符串是否为空
isEmptyString(''); // true
isEmptyString(' '); // truecontains(str, substring, caseSensitive)
检查字符串是否包含子字符串
contains('hello world', 'world'); // true
contains('hello world', 'WORLD', false); // truepad(str, length, padString, position)
字符串填充
pad('hello', 10, '0'); // 'hello00000'
pad('hello', 10, '0', 'start'); // '00000hello'toCamelCase(str, separator)
转换为驼峰命名(支持多种分隔符)
toCamelCase('hello world'); // 'helloWorld'
toCamelCase('hello_world_test'); // 'helloWorldTest'toKebabCase(str, separator)
转换为短横线命名
toKebabCase('helloWorld'); // 'hello-world'toSnakeCase(str)
转换为下划线命名
toSnakeCase('helloWorld'); // 'hello_world'toTitleCase(str)
转换为标题格式
toTitleCase('hello world'); // 'Hello World'数组工具 (Array Utils)
unique(arr)
数组去重
unique([1, 2, 2, 3]); // [1, 2, 3]groupBy(arr, key)
数组分组
groupBy([{type: 'A', value: 1}, {type: 'B', value: 2}], 'type');
// { A: [{type: 'A', value: 1}], B: [{type: 'B', value: 2}] }sortBy(arr, key, order)
数组排序
sortBy([{age: 20}, {age: 18}], 'age', 'desc');
// [{age: 20}, {age: 18}]chunk(arr, size)
数组分块
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]flatten(arr, depth)
数组扁平化
flatten([1, [2, [3]]], 2); // [1, 2, 3]shuffle(arr)
数组随机打乱
shuffle([1, 2, 3, 4]); // [3, 1, 4, 2] (随机)对象工具 (Object Utils)
deepClone(obj)
深拷贝
const obj = {a: {b: 1}};
const cloned = deepClone(obj);deepMerge(target, ...sources)
对象深合并
deepMerge({a: 1}, {b: 2}, {a: 3}); // {a: 3, b: 2}invert(obj)
对象键值对交换
invert({a: '1', b: '2'}); // {'1': 'a', '2': 'b'}pickBy(obj, predicate)
对象过滤
pickBy({a: 1, b: 0, c: 2}, (val) => val > 0); // {a: 1, c: 2}pick(obj, keys)
选择对象指定键
pick({a: 1, b: 2, c: 3}, ['a', 'c']); // {a: 1, c: 3}日期工具 (Date Utils)
formatDate(date, format)
格式化日期
formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss');
// '2023-12-01 14:30:00'getRelativeTime(date)
获取相对时间
getRelativeTime(new Date(Date.now() - 60000)); // '1分钟前'isToday(date)
判断是否为今天
isToday(new Date()); // truegetDateRange(type)
获取日期范围
getDateRange('week'); // {start: Date, end: Date}格式化工具 (Format Utils)
formatNumber(num, decimals, separator)
格式化数字
formatNumber(1234567.89, 2, ','); // '1,234,567.89'formatFileSize(bytes, decimals)
格式化文件大小
formatFileSize(1024); // '1 KB'formatCurrency(amount, currency, decimals)
格式化货币
formatCurrency(1234.56); // '¥1,234.56'formatPhone(phone)
格式化手机号
formatPhone('13812345678'); // '138-1234-5678'验证工具 (Validate Utils)
isValidEmail(email)
验证邮箱
isValidEmail('[email protected]'); // trueisValidPhone(phone)
验证手机号
isValidPhone('13812345678'); // trueisValidIdCard(idCard)
验证身份证号
isValidIdCard('110101199001011234'); // trueisValidUrl(url)
验证URL
isValidUrl('https://www.example.com'); // truevalidatePassword(password)
验证密码强度
validatePassword('MyPass123!');
// {isValid: true, strength: 'strong', message: '密码强度良好'}数学工具 (Math Utils)
randomInt(min, max)
生成指定范围内的随机整数
randomInt(1, 10); // 1-10之间的随机整数randomFloat(min, max, decimals)
生成指定范围内的随机浮点数
randomFloat(1.0, 10.0, 2); // 1.00-10.00之间的随机浮点数round(num, decimals)
数字四舍五入
round(3.14159, 2); // 3.14clamp(num, min, max)
数字限制在范围内
clamp(15, 0, 10); // 10lerp(start, end, t)
数字线性插值
lerp(0, 100, 0.5); // 50map(num, inMin, inMax, outMin, outMax)
数字映射到新范围
map(5, 0, 10, 0, 100); // 50factorial(num)
数字阶乘
factorial(5); // 120isPrime(num)
判断是否为质数
isPrime(17); // truemean(...nums)
计算平均值
mean(1, 2, 3, 4, 5); // 3median(...nums)
计算中位数
median(1, 2, 3, 4, 5); // 3存储工具 (Storage Utils)
setLocalStorage(key, value)
设置localStorage
setLocalStorage('user', {name: 'John', age: 30});getLocalStorage(key, defaultValue)
获取localStorage
getLocalStorage('user', {}); // {name: 'John', age: 30}removeLocalStorage(key)
删除localStorage
removeLocalStorage('user');setSessionStorage(key, value)
设置sessionStorage
setSessionStorage('token', 'abc123');getSessionStorage(key, defaultValue)
获取sessionStorage
getSessionStorage('token', '');setLocalStorageWithExpire(key, value, expireTime)
设置带过期时间的localStorage
setLocalStorageWithExpire('data', {value: 'test'}, 24 * 60 * 60 * 1000); // 24小时后过期URL工具 (URL Utils)
parseUrl(url)
解析URL
parseUrl('https://www.example.com/path?query=1');
// {protocol: 'https:', hostname: 'www.example.com', ...}getUrlParams(url)
获取URL参数
getUrlParams('https://example.com?name=John&age=30');
// {name: 'John', age: '30'}setUrlParams(url, params)
设置URL参数
setUrlParams('https://example.com', {name: 'John'});
// 'https://example.com?name=John'buildUrl(baseUrl, params)
构建URL
buildUrl('https://example.com', {name: 'John', age: 30});
// 'https://example.com?name=John&age=30'getDomain(url)
获取域名
getDomain('https://www.example.com/path'); // 'www.example.com'isHttps(url)
检查是否为HTTPS
isHttps('https://example.com'); // trueWorker工具 (Worker Utils)
createTimerWorker()
创建定时器Worker实例
const timer = createTimerWorker();
// 设置回调
timer.setCallbacks({
onTick: (data) => console.log('Tick:', data),
onStart: () => console.log('Timer started'),
onStop: () => console.log('Timer stopped')
});
// 开始定时器(每1秒执行一次)
timer.start({ interval: 1000 });
// 停止定时器
timer.stop();createCommonWorker()
创建公共Worker实例
const worker = createCommonWorker();
// 执行自定义函数
const result = await worker.execute(`
return args[0] + args[1];
`, [10, 20]);
console.log(result); // 30createSimpleTimer(interval, callback)
创建简单定时器
const timer = createSimpleTimer(1000, (data) => {
console.log('Timer tick:', data.timestamp);
});
// 控制定时器
timer.start();
timer.pause();
timer.resume();
timer.stop();
timer.terminate();executeFunction(func, args, timeout)
执行自定义函数(支持函数变量)
// 使用函数变量
const result = await executeFunction(
(a, b) => Math.pow(a, b),
[2, 3]
);
console.log(result); // 8
// 使用函数字符串
const arrayResult = await executeFunction(`
return args[0].map(x => x * 2);
`, [[1, 2, 3, 4, 5]]);
console.log(arrayResult); // [2, 4, 6, 8, 10]
// 使用箭头函数
const sumResult = await executeFunction(
(numbers) => numbers.reduce((sum, num) => sum + num, 0),
[[1, 2, 3, 4, 5]]
);
console.log(sumResult); // 15executeBatch(tasks, concurrency)
批量执行函数
const tasks = [
{ func: (x) => x * 2, args: [5] },
{ func: (x) => x * 3, args: [10] },
{ func: (x) => x * 4, args: [15] }
];
const results = await executeBatch(tasks, 2);
console.log(results); // [10, 30, 60]createWorkerPool(poolSize)
创建Worker池
const pool = createWorkerPool(3);
// 并发执行任务
const results = await Promise.all([
pool.execute((x) => x * 2, [5]),
pool.execute((x) => x * 3, [10]),
pool.execute((x) => x * 4, [15])
]);
console.log(results); // [10, 30, 60]
// 获取池状态
const status = pool.getStatus();
console.log(status); // { totalWorkers: 3, busyWorkers: 0, queueLength: 0 }
// 清理池
pool.terminate();createAdvancedTimer(options)
创建高级定时器
const timer = createAdvancedTimer({
interval: 1000,
maxRuns: 5,
onTick: (data, count) => console.log(`Tick ${count}:`, data),
onComplete: (count) => console.log(`Completed after ${count} runs`),
onError: (error) => console.error('Timer error:', error),
autoStart: true
});
// 控制定时器
timer.pause();
timer.resume();
timer.reset();
timer.terminate();Worker管理器方法
定时器Worker管理器 (TimerWorkerManager)
const timer = createTimerWorker();
// 基本控制
timer.start({ interval: 500 }); // 开始,每500ms执行一次
timer.pause(); // 暂停
timer.resume(); // 恢复
timer.stop(); // 停止
timer.setInterval(1000); // 设置新的间隔时间
// 状态查询
const status = timer.getStatus();
console.log(status); // { isRunning: true, interval: 1000, hasWorker: true }
// 设置回调
timer.setCallbacks({
onTick: (data) => console.log('Tick:', data),
onStart: (data) => console.log('Started with interval:', data.interval),
onStop: () => console.log('Stopped'),
onPause: () => console.log('Paused'),
onResume: () => console.log('Resumed'),
onError: (error) => console.error('Error:', error)
});
// 清理资源
timer.terminate();公共Worker管理器 (CommonWorkerManager)
const worker = createCommonWorker();
// 执行自定义函数
const result = await worker.execute(`
// 复杂的计算逻辑
let sum = 0;
for (let i = 0; i < args[0]; i++) {
sum += i * i;
}
return sum;
`, [1000]);
// 数学计算
const mathResult = await worker.calculate('2 + 3 * 4');
// 数组操作
const arrayResult = await worker.processArray([1, 2, 3, 4, 5], 'map', 2);
// 字符串操作
const stringResult = await worker.processString('hello world', 'upper');
// 对象操作
const objectResult = await worker.processObject({a: 1, b: 2}, 'keys');
// 设置回调
worker.setCallbacks({
onResult: (data, success) => console.log('Result:', data, success),
onError: (error) => console.error('Error:', error)
});
// 清理资源
worker.terminate();开发
安装依赖
npm install构建
# 生产构建
npm run build
# 开发构建
npm run build:dev
# 监听模式
npm run dev测试
npm test代码检查
npm run lint
npm run lint:fix发布到 npm
发布前准备
- 确保已登录 npm
npm login- 检查包名是否可用
npm view jn-utils- 构建项目(自动执行)
npm run build- 运行测试
npm test- 检查代码质量
npm run lint发布流程
- 更新版本号
# 补丁版本 (1.0.0 -> 1.0.1)
npm version patch
# 小版本 (1.0.0 -> 1.1.0)
npm version minor
# 大版本 (1.0.0 -> 2.0.0)
npm version major- 发布到 npm
npm publish- 发布到 GitHub(可选)
git push origin main --tags发布配置说明
files字段确保只发布dist/目录下的编译后代码prepublishOnly和prepack钩子确保发布前自动构建- 发布的内容包括:
dist/index.js- 编译后的主文件README.md- 使用文档LICENSE- 许可证文件
卫星轨道工具 (Satellite Utils)
calculateOrbitData(tleData, startTime, interval, duration)
计算轨道数据数组
const tleData = {
line1: '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
line2: '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'
};
const startTime = new Date('2023-01-01T00:00:00Z');
// 使用默认参数:1秒间隔,轨道周期持续时间
const orbitData = calculateOrbitData(tleData, startTime);
// 自定义间隔和持续时间
const orbitData2 = calculateOrbitData(tleData, startTime, 60000, 3600000); // 1分钟间隔,1小时持续时间
console.log(orbitData);
// [
// {
// // 时间信息
// time: Date,
//
// // 地理坐标信息
// longitude: 123.45, // 经度 (度)
// latitude: 45.67, // 纬度 (度)
// altitude: 400.5, // 高度 (km)
//
// // 轨道速度信息
// velocity: 7.66, // 轨道速度 (km/s)
//
// // 坐标系信息
// positionEci: { // 地心惯性坐标系位置 (km)
// x: 1234.5,
// y: 5678.9,
// z: 9012.3
// },
// velocityEci: { // 地心惯性坐标系速度 (km/s)
// x: 1.2,
// y: 3.4,
// z: 5.6
// },
// positionGd: { // 地理坐标系位置
// longitude: 2.15, // 经度 (弧度)
// latitude: 0.80, // 纬度 (弧度)
// height: 400.5 // 高度 (km)
// },
//
// // 时间系统信息
// gmst: 1.23, // 格林威治恒星时 (弧度)
//
// // 计算状态
// calculationStatus: {
// success: true,
// error: null
// }
// },
// ...
// ]calculateSatellitePosition(tleData, time)
计算指定时间点的卫星位置
const tleData = {
line1: '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
line2: '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'
};
// 计算当前时间位置
const currentPosition = calculateSatellitePosition(tleData);
console.log(currentPosition);
// {
// time: Date,
// longitude: 123.45,
// latitude: 45.67,
// altitude: 400.5,
// positionEci: {...},
// velocityEci: {...},
// positionGd: {...}
// }
// 计算指定时间位置
const specificTime = new Date('2023-01-01T12:00:00Z');
const position = calculateSatellitePosition(tleData, specificTime);getOrbitalElements(tleData)
获取轨道六根数和其他轨道数据
const tleData = {
line1: '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
line2: '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'
};
const orbitalData = getOrbitalElements(tleData);
console.log(orbitalData);
// {
// orbitalElements: {
// semiMajorAxis: {
// value: 6778.137,
// unit: 'km',
// description: '轨道椭圆的长半轴长度'
// },
// eccentricity: {
// value: 0.0006703,
// unit: '无量纲',
// description: '轨道椭圆的偏心率,0为圆轨道,1为抛物线轨道'
// },
// inclination: {
// value: 51.6416,
// unit: '度',
// description: '轨道平面与赤道平面的夹角'
// },
// rightAscensionOfAscendingNode: {
// value: 247.4627,
// unit: '度',
// description: '升交点在赤道坐标系中的经度'
// },
// argumentOfPerigee: {
// value: 130.5360,
// unit: '度',
// description: '近地点相对于升交点的角度'
// },
// meanAnomaly: {
// value: 325.0288,
// unit: '度',
// description: '卫星在轨道上的平均位置角度'
// }
// },
// additionalData: {
// orbitalPeriod: {
// value: 5553.18,
// unit: '秒',
// description: '卫星完成一次轨道运行的时间'
// },
// orbitalVelocity: {
// value: 7.66,
// unit: 'km/s',
// description: '卫星在轨道上的平均速度'
// },
// orbitType: {
// type: 'low_earth_orbit',
// code: 'LEO',
// name: '低地球轨道',
// nameEn: 'Low Earth Orbit',
// altitude: 400.0,
// altitudeRange: '160-2000 km',
// periodRange: '90-127 分钟',
// description: '主要用于地球观测、通信、科学实验等'
// },
// orbitDirection: {
// value: 'prograde',
// name: '顺行',
// description: '卫星运动方向与地球自转方向相同'
// }
// }
// }calculateVisibility(tleData, observerLocation, startTime, endTime, interval)
计算卫星可见性
const tleData = {
line1: '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
line2: '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'
};
const observerLocation = {
latitude: 39.9042,
longitude: 116.4074,
altitude: 0
};
const startTime = new Date('2023-01-01T00:00:00Z');
const endTime = new Date('2023-01-01T06:00:00Z');
const visibilityData = calculateVisibility(tleData, observerLocation, startTime, endTime);
console.log(visibilityData);
// [
// {
// time: Date,
// longitude: 123.45,
// latitude: 45.67,
// altitude: 400.5,
// elevation: 45.2,
// azimuth: 180.5,
// range: 500.0,
// isVisible: true
// },
// ...
// ]calculateOrbitPrediction(tleData, startTime, endTime, interval)
计算轨道预测
const tleData = {
line1: '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
line2: '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'
};
const startTime = new Date('2023-01-01T00:00:00Z');
const endTime = new Date('2023-01-01T06:00:00Z');
const predictionData = calculateOrbitPrediction(tleData, startTime, endTime);
console.log(predictionData);
// [
// {
// time: Date,
// longitude: 123.45,
// latitude: 45.67,
// altitude: 400.5,
// velocity: 7.66,
// positionEci: {...},
// velocityEci: {...}
// },
// ...
// ]calculateOrbitIntersections(tleData, startTime, endTime)
计算轨道交点
const tleData = {
line1: '1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
line2: '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537'
};
const startTime = new Date('2023-01-01T00:00:00Z');
const endTime = new Date('2023-01-01T06:00:00Z');
const intersections = calculateOrbitIntersections(tleData, startTime, endTime);
console.log(intersections);
// [
// {
// time: Date,
// longitude: 123.45,
// latitude: 0.0,
// type: 'ascending'
// },
// ...
// ]常用轨道函数
// 计算轨道周期
const period = calculateOrbitalPeriod(tleData);
console.log(period); // 5553.18 (秒)
// 计算轨道速度
const velocity = calculateOrbitalVelocity(tleData);
console.log(velocity); // 7.66 (km/s)
// 计算轨道高度
const altitude = calculateOrbitalAltitude(tleData);
console.log(altitude); // 400.0 (km)
// 计算轨道倾角
const inclination = calculateOrbitalInclination(tleData);
console.log(inclination); // 51.6416 (度)
// 计算轨道偏心率
const eccentricity = calculateOrbitalEccentricity(tleData);
console.log(eccentricity); // 0.0006703
// 计算轨道半长轴
const semiMajorAxis = calculateOrbitalSemiMajorAxis(tleData);
console.log(semiMajorAxis); // 6778.137 (km)
// 计算轨道远地点和近地点
const apsides = calculateOrbitalApsides(tleData);
console.log(apsides);
// {
// apogee: 6778.137,
// perigee: 6778.137,
// apogeeAltitude: 400.0,
// perigeeAltitude: 400.0
// }定时器工具 (Timer Utils)
createTimer(interval)
创建定时器实例
import { createTimer } from 'jn-utils';
// 创建1秒间隔的定时器
const timer = createTimer(1000);
// 设置回调函数
timer.setCallbacks({
onTick: (data) => console.log('Tick:', data.timestamp),
onStart: (data) => console.log('Timer started'),
onStop: (data) => console.log('Timer stopped'),
onError: (error) => console.error('Timer error:', error)
});
// 开始定时器
timer.start();
// 停止定时器
timer.stop();
// 暂停定时器
timer.pause();
// 恢复定时器
timer.resume();
// 设置新的时间间隔
timer.setInterval(2000);
// 获取状态
const status = await timer.getStatus();
console.log(status);
// 终止定时器
timer.terminate();createSimpleTimer(interval, callback)
创建简单定时器
import { createSimpleTimer } from 'jn-utils';
// 创建简单定时器
const timer = createSimpleTimer(1000, (data) => {
console.log('Tick:', data.timestamp);
});
// 控制定时器
timer.start();
timer.stop();
timer.pause();
timer.resume();
timer.setInterval(2000);
timer.terminate();createAdvancedTimer(options)
创建高级定时器
import { createAdvancedTimer } from 'jn-utils';
const timer = createAdvancedTimer({
interval: 1000,
maxRuns: 10, // 最多运行10次
onTick: (data, count) => console.log(`Tick ${count}:`, data),
onStart: (data) => console.log('Timer started'),
onStop: (data) => console.log('Timer stopped'),
onPause: (data) => console.log('Timer paused'),
onResume: (data) => console.log('Timer resumed'),
onError: (error) => console.error('Timer error:', error),
autoStart: true // 自动开始
});
// 控制定时器
timer.start();
timer.stop();
timer.pause();
timer.resume();
timer.reset(); // 重置运行计数
console.log(timer.getRunCount()); // 获取运行次数
timer.terminate();定时器管理器类 (TimerManager)
import { TimerManager } from 'jn-utils';
// 创建定时器管理器
const timerManager = new TimerManager(1000);
// 初始化
timerManager.init(2000); // 2秒间隔
// 设置回调
timerManager.setCallbacks({
onTick: (data) => {
console.log('定时器触发:', data.timestamp);
},
onStart: (data) => {
console.log('定时器开始:', data.interval);
},
onStop: (data) => {
console.log('定时器停止');
},
onPause: (data) => {
console.log('定时器暂停');
},
onResume: (data) => {
console.log('定时器恢复');
},
onError: (error) => {
console.error('定时器错误:', error);
}
});
// 控制定时器
timerManager.start();
timerManager.pause();
timerManager.resume();
timerManager.stop();
timerManager.setInterval(3000);
timerManager.terminate();定时器特性
- Web Worker支持 - 在独立线程中运行,不阻塞主线程
- 完整生命周期管理 - 初始化、开始、暂停、恢复、停止、终止
- 灵活的回调系统 - 支持多种事件回调
- 状态监控 - 实时获取定时器状态
- 错误处理 - 完善的错误处理机制
- 高级功能 - 最大运行次数、自动开始等
使用场景
// 1. 数据轮询
const dataTimer = createSimpleTimer(5000, () => {
fetchData();
});
// 2. 定时任务
const taskTimer = createAdvancedTimer({
interval: 60000, // 1分钟
maxRuns: 5, // 最多运行5次
onTick: () => performTask(),
onStop: () => console.log('任务完成')
});
// 3. 实时更新
const updateTimer = createTimer(1000);
updateTimer.setCallbacks({
onTick: () => updateUI()
});
updateTimer.start();许可证
MIT
贡献
欢迎提交 Issue 和 Pull Request!
