npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

js-next-patch

v3.2.0

Published

js 在原型上的一些常用扩展

Readme

Table of Contents

drop

从数组中删除指定索引的元素。

Parameters

  • index number 要删除的元素的索引。
  • len number 要删除的元素数量,默认为 1。 (optional, default 1)
  • edit boolean 是否修改原数组,默认为 true。 (optional, default true)

Examples

const arr = [1, 2, 3, 4, 5];
// 默认修改原数组,删除索引为 2 的元素
arr._drop(2);
console.log(arr); // 输出: [1, 2, 4, 5]
// 不修改原数组,删除索引为 0 的元素,并返回删除后的副本数组
const dropdArray = arr._drop(0, false);
console.log(arr); // 输出: [1, 2, 4, 5]
console.log(dropdArray); // 输出: [2, 4, 5]

Returns Array 被删除的元素组成的数组。

findKey

在数组中查找满足特定条件的元素的特定属性值。

Parameters

  • searchPropFunc (Function | String) 用于测试数组元素的条件函数或属性名。
  • targetProp String 要检索的目标属性的名称。
  • searchValue any? 当searchPropFunc为字符串时,用于匹配的属性值。
  • defaultValue any? 如果没有找到匹配项,返回的默认值。

Examples

const arr = [{ a: 1, b: 'test' }, { a: 2, b: 'hello' }];
const result = arr._findKey('a', 'b', 1,{}); // 返回 'test'
const arr = [{ a: 1, b: 'test' }, { a: 2, b: 'hello' }];
const result = arr._findKey((res)=>res.a===1,"b"); // 返回 'test'

Returns any 找到的属性值或默认值。第一个参数为函数情况下,第二个参数则是第一个函数第一次返回 true 时需要返回数据的键值,第三个参数为 默认值 第一个参数为字符串,则会取第一个参数和第三个参数的值比较,如果为 true ,返回第二个参数键值的取值,第四个参数为默认值

head

获取数组的第一个元素。

Examples

[]._head() // undefined
[0]._head() // 0

Returns any 返回数组的第一个元素,如果数组为空则返回undefined。

last

获取数组的最后一个元素。

Examples

[]._last() // undefined
[0]._last() // 0

Returns any 返回数组的最后一个元素,如果数组为空则返回undefined。

debounce

防抖函数:在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。

Parameters

  • func Function 需要防抖处理的函数
  • wait number 等待时间,单位为毫秒
  • immediate boolean 是否立即执行,如果为 true,则在 wait 时间内部分的开始调用函数 (optional, default false)

Examples

import { debounce } from 'js-next-patch';

// 使用示例:创建一个防抖函数,当用户停止输入后 500ms 执行
const debouncedSave = debounce(function(input) {
  saveInput(input);
}, 500);

debouncedSave.cancel(); // 取消防抖函数,在 vue 组件销毁时调用

// 在 input 事件监听中使用
inputElement.addEventListener('input', (event) => {
  debouncedSave(event.target.value);
});

// 如果需要立即执行的防抖函数
const debouncedImmediate = debounce(function() {
  console.log('立即执行,然后等待停止触发后 500ms 再次执行');
}, 500, true);

// 使用立即执行的防抖函数
button.addEventListener('click', debouncedImmediate);

Returns Function 返回一个具有防抖能力的函数

debounce

防抖函数:在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。

Parameters

  • func Function 需要防抖处理的函数
  • wait number 等待时间,单位为毫秒
  • immediate boolean 是否立即执行,如果为 true,则在 wait 时间内部分的开始调用函数 (optional, default false)

Examples

// 使用示例:创建一个防抖函数,当用户停止输入后 500ms 执行
const debouncedSave = Object._debounce(function(input) {
  saveInput(input);
}, 500);

debouncedSave.cancel(); // 取消防抖函数,在 vue 组件销毁时调用

// 在 input 事件监听中使用
inputElement.addEventListener('input', (event) => {
  debouncedSave(event.target.value);
});

// 如果需要立即执行的防抖函数
const debouncedImmediate = Object._debounce(function() {
  console.log('立即执行,然后等待停止触发后 500ms 再次执行');
}, 500, true);

// 使用立即执行的防抖函数
button.addEventListener('click', debouncedImmediate);

Returns Function 返回一个具有防抖能力的函数

delay

创建一个延迟执行的Promise,完成后调用回调函数。

Parameters

  • time number 延迟时间,单位为毫秒。 (optional, default 500)
  • callBack Function? 延迟完成后执行的回调函数。

Examples

import { delay } from 'js-next-patch';
await delay(1000, () => {})

Returns Promise 返回一个Promise对象,在指定时间后解决。

downloadFile

生成一个 a 标签 下载文件。

Parameters

  • url string 文件的URL地址。
  • name string 下载文件的名称,默认为"未命名"。 (optional, default "未命名")
  • flx string 下载文件的扩展名,默认为".xlsx"。 (optional, default ".xlsx")

Examples

import { downloadFile } from "js-next-patch";
downloadFile("https://www.example.com/file.xlsx");

Returns void

downloadStream

使用接口的方式下载流数据。

Parameters

  • res Object 包含流数据的响应对象。
  • name string 下载文件的名称,默认为"未命名"。 (optional, default "未命名")
  • flx string 下载文件的扩展名,默认为".xlsx"。 (optional, default ".xlsx")
  • type string 下载文件的 MIME 类型,默认为"application/vnd.ms-excel", type 不正确的情况下,在 IOS 下可能会出现下载失败的情况 (optional, default "application/vnd.ms-excel")

Examples

import { downloadStream } from "js-next-patch";
downloadStream(res, "文件名", ".xlsx"); // res 指的是接口返回的响应对象

Returns void

isBeyond

hover 等事件判断文本是否超出容器宽度。

Parameters

Examples

import { isBeyond } from 'js-next-patch';

<div on-click={this.handleClick} ></div>

handleClick = (e) => {
  if (isBeyond(e)) {
    console.log('beyond');
    console.log(e);
  }
}

Returns boolean 如果文本超出容器宽度,则返回 true;否则返回 false。

retry

异步重试函数,直到操作成功或达到最大重试次数。

Parameters

  • options Object 重试配置

    • options.times number 最大重试次数 (optional, default 3)
    • options.delay (number | null)? 两次重试之间固定的延迟时间(毫秒)
    • options.backoff function? 重试间隔函数,返回每次重试的延迟时间(毫秒) 接受当前尝试次数作为参数,如(i) => i * 1000(实现指数退避)
  • func function 异步操作函数,接受一个退出回调函数作为参数 当异步操作失败时,调用退出回调并传入错误信息 成功时返回形如 [null, result] 的数组,失败时抛出错误

Examples

import { retry } from "js-next-patch";

const tryit = (fn) => fn;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 现在我们可以使用retry函数了
const myAsyncFunction = (exit) => {
// 这里是你的异步操作
 return new Promise((resolve, reject) => {
 // 模拟网络请求或其他异步操作
     setTimeout(() => {
        if (Math.random() > 0.7) { // 模拟70%的成功率
             resolve({ data: 'success' });
         } else {
             reject(new Error('Operation failed'));
         }
     }, 1000);
 }).catch(exit);
};

// 使用retry函数

retry({
     times: 5,
     delay: 2000, // 每次重试等待2秒
     backoff: (count) => count * 1000 // 指数退避,每次重试间隔翻倍
},
    myAsyncFunction
).then((result) => {
    console.log('Success:', result);
 }).catch((error) => {
    console.error('Failed after retries:', error);
});
  • Throws Error 在达到最大重试次数后,抛出最后一次出现的错误

Returns Promise<TResponse> 当异步操作成功时,返回操作的结果

throttle

创建一个节流函数,在 wait 毫秒内最多执行 func 一次的函数。 提供一个 cancel 方法取消延迟的函数调用。

Parameters

  • func Function 需要节流的函数。
  • wait number 执行操作的间隔时间,单位毫秒。

Examples

import { throttle } from 'js-next-patch';

// 使用示例:创建一个节流函数,当用户连续滚动页面时,每 200ms 最多执行一次
const throttledScroll = Object._throttle(function() {
  console.log('Scroll event triggered');
}, 200);

// 在 scroll 事件监听中使用
window.addEventListener('scroll', throttledScroll);

// 如果需要取消节流控制的函数
// 可以在组件销毁或者卸载事件监听器时调用
window.removeEventListener('scroll', throttledScroll);
throttledScroll.cancel();

Returns Function 返回节流控制的函数。

throttle

创建一个节流函数,在 wait 毫秒内最多执行 func 一次的函数。 提供一个 cancel 方法取消延迟的函数调用。

Parameters

  • func Function 需要节流的函数。
  • wait number 执行操作的间隔时间,单位毫秒。

Examples

// 使用示例:创建一个节流函数,当用户连续滚动页面时,每 200ms 最多执行一次
const throttledScroll = Object._throttle(function() {
  console.log('Scroll event triggered');
}, 200);

// 在 scroll 事件监听中使用
window.addEventListener('scroll', throttledScroll);

// 如果需要取消节流控制的函数
// 可以在组件销毁或者卸载事件监听器时调用
window.removeEventListener('scroll', throttledScroll);
throttledScroll.cancel();

Returns Function 返回节流控制的函数。

format

格式化日期对象为指定格式的字符串。

Parameters

  • fmt string 格式化字符串的格式。 (optional, default "yyyy-MM-dd hh:mm:ss")

Examples

new Date()._format("yyyy-MM-dd");
new Date()._Format("yyyy-MM-dd hh:mm:ss");
new Date()._Format("yyyy年MM月dd日 hh时mm分ss秒");
new Date()._Format("yyyy年MM月dd日 hh时mm分ssS秒");

Returns string 格式化后的日期字符串。

isRange

判断当前日期是否在指定的日期范围内。

Parameters

  • startOption (Date | {value: Date, include: boolean} | -1) 开始日期,可以是 Date 对象、包含日期和是否包含该日期的对象,或者 -1 表示不限制开始时间。
  • endOption (Date | {value: Date, include: boolean} | -1) 结束日期,可以是 Date 对象、包含日期和是否包含该日期的对象,或者 -1 表示不限制结束时间。

Examples

const date = new Date();
传入 -1 表示不限制开始或结束时间
console.log(date._isRange(-1, new Date())); // true
console.log(date._isRange(new Date(), -1)); // true
传入对象,指定日期和是否包含当前传入的日期
console.log(date._isRange({ value: new Date(), include: false }, { value: new Date(), include: false })); // false
  • Throws Error 如果传入的参数格式无效,将抛出错误。

Returns boolean 如果当前日期在指定的日期范围内,则返回 true,否则返回 false。

oneDay

返回一天的毫秒数

Examples

Date._ONE_DAY; // 86400000

Returns number 返回一天的毫秒数

oneHour

返回一小时的毫秒数

Examples

Date._ONE_HOUR; // 3600000

Returns number 返回一小时的毫秒数

isValid

为 Object 类定义一个名为 _isValid 的方法,用于校验给定的值。

Parameters

  • value any 需要校验的值。
  • condition (Function | Array | Object) 校验规则,可以是一个函数、函数数组或者函数组成的对象。 (optional, default ()=>true)
  • callback Function 一个可选的回调函数,如果提供,将会用校验的值、条件和结果作为参数调用它,并返回回调的结果。 (optional, default undefined)

Examples

function isNumber(value) {
   return typeof value === 'number';
}

function isString(value) {
   return typeof value === 'string';
}

示例回调函数
function callback(value, condition, result) {
   console.log(`校验值: ${value}`);
   console.log(`校验规则: ${condition}`);
   console.log(`校验结果: ${result}`);
   return result ? '校验通过' : '校验失败';
}

使用示例 1: 单个校验函数
let result1 = Function._isValid(123, isNumber);
console.log(result1); // 应该输出 true

使用示例 2: 校验函数数组
let result2 = Function._isValid('abc', [isNumber, isString]);\
console.log(result2); // 应该输出 false,因为 'abc' 不是数字

使用示例 3: 校验函数组成的对象
let result3 = Function._isValid('abc', { isNum: isNumber, isStr: isString });
console.log(result3); // 应该输出 false,因为 'abc' 不是数字

使用示例 4: 带回调函数的校验
let result4 = Function._isValid('abc', isString, callback);
应该在控制台输出:
校验值: abc
校验规则: function isString(value) { return typeof value === 'string'; }
校验结果: true
console.log(result4); // 应该输出 '校验通过'
  • Throws Error 如果 condition 不是函数、函数数组或函数组成的对象,将抛出错误。

Returns any 如果提供了回调函数,则返回回调函数的返回值;否则返回校验结果。

promisify

将基于回调的函数(例如 Node.js 风格的回调函数)转换为返回 Promise 的函数。

Parameters

  • originalFunction Function 需要转换的原始函数
  • thisArg Object? 当调用原始函数时,用作 this 的值

Examples

// 使用示例:将 setTimeout 转换为 Promise 形式
const setTimeoutPromise = Function._promisify(setTimeout, global);
setTimeoutPromise(1000).then(() => {
  console.log('1秒后打印这条信息');
});
// 使用示例:将 Node.js 风格的 fs.readFile 转换为 Promise 形式
const fs = require('fs');
const readFilePromise = Function._promisify(fs.readFile, fs);
readFilePromise('./example.txt', 'utf8').then((data) => {
  console.log(data);
}).catch((error) => {
  console.error('读取文件时发生错误:', error);
});

Returns Function 返回一个新的函数,该函数返回一个 Promise

typeof

在 Object 对象上定义一个新的静态方法 typeof,用于检查值的类型,并根据检查结果执行回调函数。

Parameters

  • value any 需要检查类型的值。
  • types (string | Array<string>) 一个或多个预期的类型字符串。
  • callBack function? 一个可选的回调函数,如果提供并且是函数类型, 则会将类型检查的布尔结果作为参数调用此函数,并返回函数的返回值。

Examples

// 使用示例
// 检查 "Hello" 是否为字符串类型,并提供一个回调函数处理结果
Function._typeof("Hello", "string", function(isString) {
  console.log(`是否字符串:${isString}`);
});
// 输出:"是否字符串:true"

// 检查 100 是否为数字类型,不提供回调函数
const isNumber = Function._typeof(100, "number");
console.log(isNumber); // 输出:true

// 检查一个对象是否为数组或对象类型,并提供一个回调函数返回自定义的结果
const result = Function._typeof({}, ["array", "object"], function(isCorrectType) {
  return isCorrectType ? '匹配预期类型' : '不匹配预期类型';
});
console.log(result); // 输出:"匹配预期类型"

Returns (boolean | any) 如果未提供回调函数,或回调函数不是函数类型,则直接返回类型检查的布尔结果; 如果提供了回调函数并且是函数类型,则返回回调函数的调用结果。

isNumber

判断一个值是否为数字。

Parameters

  • value any 要检查的值。
  • allowDecimals boolean 是否允许小数,默认为true。 (optional, default true)
  • checkString boolean 是否检查字符串表示的数字,默认为true。 (optional, default true)

Examples

// 默认允许小数,返回true
Number._isNumber(5.0);

// 不允许小数,返回true
Number._isNumber(5.0, false);

// 默认允许小数,检查字符串表示的数字,返回true
Number._isNumber("5.0");

// 不允许小数,检查字符串表示的数字,返回false
Number._isNumber("5.0", false);

// 不检查字符串表示的数字,返回false
Number._isNumber("5.0", true, false);

Returns boolean 如果值是数字,则返回true;否则返回false。

maxSafeParamsInteger

返回一个最大安全接口参数整数

Examples

Number._MAX_SAFE_PARAMS_INTEGER; // 2147483647

Returns number 最大安全参数整数

toNumber

将给定的值转换为数字。

Parameters

  • value any 要转换的值。
  • allowDecimals boolean 是否允许小数。 (optional, default true)
  • defaultVal any 如果转换失败,返回的默认值。 (optional, default undefined|function)

Examples

// 返回 123
Number._toNumber("123");

// 返回 123.45
Number._toNumber("123.45", true);

// 返回 123,忽略小数部分
Number._toNumber("123.45", false);

// 返回默认值10
Number._toNumber("abc", true, 10);

// 返回默认值,通过函数计算得出
Number._toNumber("abc", true, () => 10);

Returns (number | any) 转换后的数字或默认值。

cloneDeep

深度克隆一个值。

Parameters

  • value any 要克隆的值。
  • map WeakMap 用于处理循环引用的WeakMap实例。 (optional, default newWeakMap())

Examples

const original = {
  number: 1,
  bool: false,
  str: 'string',
  arr: [1, 2, 3],
  obj: { nested: 'object' },
  date: new Date(),
  regexp: new RegExp('\\w+'),
  map: new Map([['key', 'value']]),
  set: new Set([1, 2, 3])
};

const cloned = Object._cloneDeep(original);

console.log(cloned);

Returns any 返回克隆后的值。

isEmpty

判断一个对象是否为空。 对于数组和字符串,检查其长度是否为0; 对于Map和Set对象,检查其大小是否为0; 对于普通对象,检查是否没有任何自身的可枚举属性。 注意:null和undefined不被视为对象,函数将会返回false。

Parameters

  • obj Object 需要检查的对象。

Examples

Object._isEmpty({}); // 返回 true
Object._isEmpty([]); // 返回 true
Object._isEmpty(new Map()); // 返回 true
Object._isEmpty({ key: 'value' }); // 返回 false
Object._isEmpty(null); // 返回 false
Object._isEmpty(undefined); // 返回 false
Object._isEmpty(123); // 返回 false

const obj = { key: 'value' };
obj._isEmpty(); // 返回 false

Returns boolean 如果对象为空,则返回true,否则返回false。

isEqual

深度比较两个值是否相等,并可选地使用回调函数处理比较结果。

Parameters

  • value any 第一个要比较的值。
  • other any 第二个要比较的值。
  • callback Function? 可选的回调函数,用于处理比较结果。接受三个参数:比较结果、第一个值和第二个值。

Examples

// 返回 true
Object._isEqual({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } });
// 返回 false
Object._isEqual({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 3 } });
// 返回 true
Object._isEqual([1, 2, 3], [1, 2, 3]);
// 返回 false
Object._isEqual([1, 2, 3], [1, 2, 4]);
// 使用回调函数返回 "equal" 或 "not equal"
Object._isEqual({ a: 1 }, { a: 1 }, (result) => result ? "equal" : "not equal");

Returns any 如果提供了回调函数,则返回回调函数的返回值;否则返回比较结果的布尔值。

isObject

判断一个值是否为对象。

Parameters

  • value any 要判断的值。

Examples

console.log(Object._isObject({})); // 输出: true
console.log(Object._isObject([])); // 输出: false
console.log(Object._isObject(null)); // 输出: false
console.log(Object._isObject(42)); // 输出: false
console.log(Object._isObject("Hello")); // 输出: false
console.log(Object._isObject(function () {})); // 输出: false

Returns boolean 如果值是对象,则返回true;否则返回false。

omit

从对象中排除指定的属性,返回新对象,只能排除对象自身的属性,不能排除继承的属性,并且只能排除一级属性。

Parameters

  • keysToOmit ...(string | Array<string>) 要排除的属性,可以是一个参数列表或一个包含属性的数组。

Examples

const obj = { a: 1, b: 2, c: 3 };
const result1 = obj._omit('a', 'c');
console.log(result1); // 输出: { b: 2 }
const result2 = obj._omit(['b', 'c']);
console.log(result2); // 输出: { a: 1 }

Returns Object 排除指定属性后的新对象。

omitDeep

在对象的原型上定义一个方法,用于深拷贝当前对象并省略指定的键。

Parameters

  • omit Array<string> 需要从克隆结果中省略的属性名称数组。 (optional, default [])
  • map WeakMap 用于追踪已克隆对象以处理循环引用的WeakMap对象。 (optional, default newWeakMap())

Examples

const originalObject = {
          name: "张三",
          age: 30,
          contact: {
             email: "[email protected]",
             phone: "123456789",
         },
         hobbies: ["篮球", "游泳"],
  };

克隆对象,但省略 'contact' 和 'hobbies' 键,只能省略一层
const clonedObject = originalObject._omitDeep(['contact', 'hobbies']);
console.log(clonedObject); // 输出: { name: '张三', age: 30 }
注意:'contact' 和 'hobbies' 属性不会出现在 clonedObject 中

Returns Object 克隆后的对象,省略了指定的键。

pick

从对象中挑选指定的键并返回由这些键组成的对象,只能排除对象自身的属性,不能排除继承的属性,并且只能排除一级属性。

Parameters

Examples

const obj = { name: 'John', age: 30}
const pickedObj = obj._pick('name', 'age');
console.log(pickedObj); // 输出: { name: 'John', age: 30 }
const obj = { name: 'John', age: 30}
const pickedObj = obj._pick(['name', 'age']);
console.log(pickedObj); // 输出: { name: 'John', age: 30 }

Returns Object 只包含指定键的新对象。

pickDeep

创建对象的深层克隆,但只包含指定的键

Parameters

  • pick Array<string> 一个字符串数组,代表要从对象中挑选的键。
  • map WeakMap 一个可选的WeakMap,用于追踪循环引用。 (optional, default newWeakMap())

Examples

const original = { a: 1, b: { c: 2, d: 3 } };
const picked = original._pickDeep(['a', 'b.c']);
console.log(picked); // { a: 1, b: { c: 2 } }
  • Throws TypeError 如果 'pick' 不是字符串数组或者 'map' 不是WeakMap实例,则抛出错误。

Returns Object 一个新对象,只包含挑选的键。

generateRandomColor

生成随机颜色的字符串表示形式。

Examples

String._generateRandomColor(); // #93814f

Returns string 生成的随机颜色字符串,格式为 "#RRGGBB"。

generateRandomString

生成指定长度的随机字符串。

Parameters

  • length number 生成的随机字符串的长度,默认为 6。 (optional, default 6)

Examples

String._generateRandomString(10); // '0123456789'

Returns string 生成的随机字符串。

toDate

如果字符串代表一个有效的日期字符串,则将其转换为 Date 对象。 如果字符串不是有效的日期,则返回 false

Examples

// 对于有效的日期字符串,返回 Date 对象
"2021-12-31"._toDate();
// 对于无效的日期字符串,返回 false
"这不是一个日期"._toDate();

Returns (Date | false) 对应于字符串的 Date 对象,或者如果字符串不是有效日期时返回 false

trimAll

移除字符串中所有的空白字符,包括空格、制表符、换行符等。

Examples

"aaaa bbbb".trimAll(); // "aaaabbbb"

Returns string 返回移除所有空白字符后的字符串。