Installations
npm install mazey
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
16.20.2
NPM Version
8.19.4
Score
74.6
Supply Chain
99.5
Quality
88.8
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (60.2%)
JavaScript (39.22%)
Shell (0.59%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
Download Statistics
Total Downloads
28,049
Last Day
1
Last Week
11
Last Month
450
Last Year
5,954
GitHub Statistics
MIT License
4 Stars
1,167 Commits
2 Forks
2 Watchers
40 Branches
1 Contributors
Updated on Feb 13, 2025
Bundle Size
35.63 kB
Minified
11.51 kB
Minified + Gzipped
Package Meta Information
Latest Version
4.7.12
Package Id
mazey@4.7.12
Unpacked Size
217.47 kB
Size
55.21 kB
File Count
36
NPM Version
8.19.4
Node Version
16.20.2
Published on
Jan 11, 2025
Total Downloads
Cumulative downloads
Total Downloads
28,049
Last Day
0%
1
Compared to previous day
Last Week
-83.3%
11
Compared to previous week
Last Month
0.9%
450
Compared to previous month
Last Year
-49.1%
5,954
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
48
English | 简体中文
Mazey
Mazey is a functional library for daily front-end work. There are already many excellent libraries for front-end development, but creating a file named utils.js
or common.js
is generally used to supply common functions in projects. It's boring to copy similar functions across multiple projects. That's why I've created this library and will keep updating it to serve as a reliable resource for front-end needs.
Install
Use Mazey via npm.
1npm install mazey --save
Use Mazey from CDN.
1<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mazey@latest/lib/mazey.min.js"></script>
Of course, you can also download and serve the file lib/mazey.min.js yourself.
Usage
Example: Use a function to verify if a value is a number suitable for standard calculations and comparisons.
Import from npm.
1import { isNumber } from "mazey"; 2 3const x = 123; 4const y = Infinity; 5// <=> typeof x === "number" && !isNaN(x) && isFinite(x) 6isNumber(x); // Output: true 7isNumber(y); // Output: false
Import from CDN.
1<script type="text/javascript" src="//i.mazey.net/mazey/lib/mazey.min.js"></script> 2<script> 3 const x = Infinity; 4 // <=> typeof x === "string" && !isNaN(x) 5 mazey.isNumber(x, { isInfinityAsNumber: true }); // Output: true 6</script>
API Examples
There are some examples maintained by hand below. For more information, please check the full documentation.
Table of Contents
- Generated with ❤️
- Load Resource
- Util
- URL
- Store
- DOM
- Calculate and Formula
- Browser Information
- Web Performance
- Debug
Load Resource
loadScript
Load a JavaScript file from the server and execute it.
Usage:
1loadScript( 2 "http://example.com/static/js/plugin-2.1.1.min.js", 3 { 4 id: "iamid", // (Optional) script ID, default none 5 timeout: 5000, // (Optional) timeout, default `5000` 6 } 7 ) 8 .then( 9 res => { 10 console.log(`Load JavaScript script: ${res}`); 11 } 12 ) 13 .catch( 14 err => { 15 console.error(`Load JavaScript script: ${err.message}`); 16 } 17 );
Output:
1Load JavaScript script: loaded
loadScriptIfUndefined
Load a script from the given URL if it (window["attribute"]
) has not already been loaded.
Usage:
1loadScriptIfUndefined("xyz", "https://example.com/lib/xyz.min.js") 2 .then(() => { 3 console.log("xyz is loaded."); 4 }) 5 .catch(err => { 6 console.log("Failed to load xyz.", err); 7 });
Output:
1xyz is loaded.
loadCSS
Load a CSS file from the server.
Usage:
1loadCSS( 2 "https://example.com/path/example.css", 3 { 4 id: "iamid", // Optional, link ID, default none 5 } 6 ) 7 .then( 8 res => { 9 console.log(`Load CSS Success: ${res}`); 10 } 11 ) 12 .catch( 13 err => { 14 console.error(`Load CSS Fail: ${err.message}`) 15 } 16 );
Output:
1Load CSS Success: loaded
loadImage
Load an image from the given URL.
The target image will be loaded in the background, and the Promise status will change after the image is loaded. If the image fails to load, the Promise status will change to reject
with the error object. If the image is loaded successfully, the Promise status will change to resolve
with the image object. This method can be used to preload images and cache them in the browser. It can also be used to implement lazy loading of images.
Note that this method will not add the image to the DOM.
Usage:
1loadImage("https://example.com/example.png") 2 .then((img) => { 3 console.log(img); 4 }) 5 .catch((err) => { 6 console.log(err); 7 });
windowLoaded
Check whether the page is loaded successfully (Keep the compatibility if the browser's load
event has been triggered).
Usage:
1windowLoaded() 2 .then(res => { 3 console.log(`Load Success: ${res}`); 4 }) 5 .catch(err => { 6 console.log(`Load Timeout or Fail: ${err.message}`); 7 });
Output:
1Load Success: load
Util
isNumber
Check whether it is a right number.
Usage:
1const ret1 = isNumber(123); 2const ret2 = isNumber("123"); 3// Default: NaN, Infinity is not Number 4const ret3 = isNumber(Infinity); 5const ret4 = isNumber(Infinity, { isInfinityAsNumber: true }); 6const ret5 = isNumber(NaN); 7const ret6 = isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true }); 8console.log(ret1, ret2, ret3, ret4, ret5, ret6);
Output:
1true false false true false true
isJSONString
Check whether it is a valid JSON string.
Usage:
1const ret1 = isJSONString(`['a', 'b', 'c']`); 2const ret2 = isJSONString(`["a", "b", "c"]`); 3console.log(ret1); 4console.log(ret2);
Output:
1false 2true
isValidData
Determine the validity of the data.
Usage:
1const validData = { 2 a: { 3 b: { 4 c: 413 5 } 6 } 7}; 8const isValidDataResA = isValidData(validData, ["a", "b", "c"], 2333); 9const isValidDataResB = isValidData(validData, ["a", "b", "c"], 413); 10const isValidDataResC = isValidData(validData, ["d", "d"], 413); 11console.log("isValidDataResA:", isValidDataResA); 12console.log("isValidDataResB:", isValidDataResB); 13console.log("isValidDataResC:", isValidDataResC);
Output:
1isValidDataResA: false 2isValidDataResB: true 3isValidDataResC: false
genRndNumString
Produce a random string of number, genRndNumString(7)
=> "7658495".
Usage:
1const ret1 = genRndNumString(4); 2const ret2 = genRndNumString(7); 3console.log(ret1); 4console.log(ret2);
Output:
19730 22262490
formatDate
Return the formatted date string in the given format.
Usage:
1const ret1 = formatDate(); 2const ret2 = formatDate("Tue Jan 11 2022 14:12:26 GMT+0800 (China Standard Time)", "yyyy-MM-dd hh:mm:ss"); 3const ret3 = formatDate(1641881235000, "yyyy-MM-dd hh:mm:ss"); 4const ret4 = formatDate(new Date(2014, 1, 11), "MM/dd/yyyy"); 5console.log("Default formatDate value:", ret1); 6console.log("String formatDate value:", ret2); 7console.log("Number formatDate value:", ret3); 8console.log("Date formatDate value:", ret4);
Output:
1Default formatDate value: 2023-01-11 2String formatDate value: 2022-01-11 14:12:26 3Number formatDate value: 2022-01-11 14:07:15 4Date formatDate value: 02/11/2014
debounce
Debounce
Usage:
1const foo = debounce(() => { 2 console.log("The debounced function will only be invoked in 1000 milliseconds, the other invoking will disappear during the wait time."); 3}, 1000, true);
throttle
Throttle
Usage:
1const foo = throttle(() => { 2 console.log("The function will be invoked at most once per every wait 1000 milliseconds."); 3}, 1000, { leading: true });
Reference: Lodash
convertCamelToKebab
Transfer CamelCase to KebabCase.
Usage:
1const ret1 = convertCamelToKebab("ABC"); 2const ret2 = convertCamelToKebab("aBC"); 3console.log(ret1); 4console.log(ret2);
Output:
1a-b-c 2a-b-c
convertCamelToUnder
Transfer CamelCase to Underscore.
Usage:
1const ret1 = convertCamelToUnder("ABC"); 2const ret2 = convertCamelToUnder("aBC"); 3console.log(ret1); 4console.log(ret2);
Output:
1a_b_c 2a_b_c
deepCopy
Copy/Clone Object deeply.
Usage:
1const ret1 = deepCopy(["a", "b", "c"]); 2const ret2 = deepCopy("abc"); 3console.log(ret1); 4console.log(ret2);
Output:
1["a", "b", "c"] 2abc
URL
getQueryParam
Get the query param's value of the current Web URL(location.search
).
Usage:
1// http://example.com/?t1=1&t2=2&t3=3&t4=4#2333 2// ?t1=1&t2=2&t3=3&t4=4 3const p1 = getQueryParam("t3"); 4const p2 = getQueryParam("t4"); 5console.log(p1, p2);
Output:
13 4
getUrlParam
Returns the value of the specified query parameter in the input URL.
Usage:
1const p1 = getUrlParam("https://example.com/?t1=1&t2=2&t3=3&t4=4", "t3"); 2const p2 = getUrlParam("https://example.com/?t1=1&t2=2&t3=3&t4=4", "t4"); 3console.log(p1, p2);
Output:
13 4
getHashQueryParam
Get the hash query param's value of the current Web URL(location.hash
).
Usage:
1// http://example.com/?#2333?t1=1&t2=2&t3=3&t4=4 2// #2333?t1=1&t2=2&t3=3&t4=4 3const p1 = getHashQueryParam("t3"); 4const p2 = getHashQueryParam("t4"); 5console.log(p1, p2);
Output:
13 4
getDomain
Get the domain of URL, and other params.
Usage:
1const ret1 = getDomain("http://example.com/?t1=1&t2=2&t3=3&t4=4"); 2const ret2 = getDomain("http://example.com/test/thanks?t1=1&t2=2&t3=3&t4=4", ["hostname", "pathname"]); 3const ret3 = getDomain("http://example.com:7890/test/thanks", ["hostname"]); 4const ret4 = getDomain("http://example.com:7890/test/thanks", ["host"]); // With Port 5const ret5 = getDomain("http://example.com:7890/test/thanks", ["origin"]); 6const ret6 = getDomain("http://example.com:7890/test/thanks?id=1", ["origin", "pathname", "search"]); 7console.log(ret1); 8console.log(ret2); 9console.log(ret3); 10console.log(ret4); 11console.log(ret5); 12console.log(ret6);
Output:
1example.com 2example.com/test/thanks 3example.com 4example.com:7890 5http://example.com:7890 6http://example.com:7890/test/thanks?id=1
updateQueryParam
Update the query param's value of the input URL.
Usage:
1const ret1 = updateQueryParam("http://example.com/?t1=1&t2=2&t3=3&t4=4", "t3", "three"); 2const ret2 = updateQueryParam("http://example.com/?t1=1&t2=2&t3=3&t4=4", "t4", "four"); 3console.log(ret1); 4console.log(ret2);
Output:
1http://example.com/?t1=1&t2=2&t3=three&t4=4 2http://example.com/?t1=1&t2=2&t3=3&t4=four
isValidUrl
Checks if the given string is a valid URL, including scheme URLs.
Usage:
1const ret1 = isValidUrl("https://www.example.com"); 2const ret2 = isValidUrl("http://example.com/path/exx/ss"); 3const ret3 = isValidUrl("https://www.example.com/?q=hello&age=24#world"); 4const ret4 = isValidUrl("http://www.example.com/#world?id=9"); 5const ret5 = isValidUrl("ftp://example.com"); 6console.log(ret1, ret2, ret3, ret4, ret5);
Output:
1true true true true true
If you are specifically checking for HTTP/HTTPS URLs, it is recommended to use the isValidHttpUrl
function instead.
The isValidUrl
function matches all scheme URLs, including FTP and other non-HTTP schemes.
isValidHttpUrl
Check if the given string is a valid HTTP/HTTPS URL.
Usage:
1const ret1 = isValidHttpUrl("https://www.example.com"); 2const ret2 = isValidHttpUrl("http://example.com/path/exx/ss"); 3const ret3 = isValidHttpUrl("https://www.example.com/?q=hello&age=24#world"); 4const ret4 = isValidHttpUrl("http://www.example.com/#world?id=9"); 5const ret5 = isValidHttpUrl("ftp://example.com"); 6console.log(ret1, ret2, ret3, ret4, ret5);
Output:
1true true true true false
Store
Cookie
Handle Cookie.
Usage:
1setCookie("test", "123", 30, "example.com"); // key value day domain 2const ret = getCookie("test"); 3console.log(ret);
Output:
1123
Storage
Handle Storage (Keep fit for JSON, it can transfer format automatically).
Usage:
1setSessionStorage("test", "123"); 2const ret1 = getSessionStorage("test"); 3setLocalStorage("test", "123"); 4const ret2 = getLocalStorage("test"); 5console.log(ret1, ret2); 6 7// or package in usage 8const projectName = "mazey"; 9function mSetLocalStorage (key, value) { 10 return setLocalStorage(`${projectName}_${key}`, value); 11} 12 13function mGetLocalStorage (key) { 14 return getLocalStorage(`${projectName}_${key}`); 15}
Output:
1123 123
DOM
addStyle
Add <style>
in <head>
.
Example 1: Add the <style>
with id
, and repeated invoking will update the content instead of adding a new one.
1addStyle( 2 ` 3 body { 4 background-color: #333; 5 } 6 `, 7 { 8 id: "test", 9 } 10); 11// <style id="test"> 12// body { 13// background-color: #333; 14// } 15// </style>
Example 2: Add the <style>
without id
, and repeated invoking will add a new one.
1addStyle( 2 ` 3 body { 4 background-color: #444; 5 } 6 ` 7); 8// <style> 9// body { 10// background-color: #444; 11// } 12// </style>
Class
Modify class
.
Usage:
1const dom = document.querySelector("#box"); 2 3// Determine `class` 4hasClass(dom, "test"); 5// Add `class` 6addClass(dom, "test"); 7// Remove `class` 8removeClass(dom, "test");
newLine
Make a new line of HTML.
Usage:
1const ret1 = newLine("a\nb\nc"); 2const ret2 = newLine("a\n\nbc"); 3console.log(ret1); 4console.log(ret2);
Output:
1a<br />b<br />c 2a<br /><br />bc
Calculate and Formula
inRate
Hit probability (1% ~ 100%).
Usage:
1const ret = inRate(0.5); // 0.01 ~ 1 true/false 2console.log(ret);
Output:
1true
Example: Test the precision.
1// Test 2let trueCount = 0; 3let falseCount = 0; 4new Array(1000000).fill(0).forEach(() => { 5 if (inRate(0.5)) { 6 trueCount++; 7 } else { 8 falseCount++; 9 } 10}); 11console.log(trueCount, falseCount); // 499994 500006
longestComSubstring
Computes the longest common substring of two strings.
Usage:
1const ret = longestComSubstring("fish", "finish"); 2console.log(ret);
Output:
13
longestComSubsequence
Computes the longest common subsequence of two strings.
Usage:
1const ret = longestComSubsequence("fish", "finish"); 2console.log(ret);
Output:
14
Browser Information
getBrowserInfo
Browser Information
Usage:
1const ret = getBrowserInfo(); 2console.log(ret);
Output:
1{"engine":"webkit","engineVs":"537.36","platform":"desktop","supporter":"chrome","supporterVs":"85.0.4183.121","system":"windows","systemVs":"10"}
Results:
Attribute | Description | Type | Values |
---|---|---|---|
system | System | string | android, ios, windows, macos, linux |
systemVs | System version | string | Windows: 2000, xp, 2003, vista, 7, 8, 8.1, 10 macOS: ... |
platform | Platform | string | desktop, mobile |
engine | Engine | string | webkit, gecko, presto, trident |
engineVs | Engine version | string | - |
supporter | Supporter | string | edge, opera, chrome, safari, firefox, iexplore |
supporterVs | Supporter version | string | - |
shell | Shell | string | (Optional) wechat, qq_browser, qq_app, uc, 360, 2345, sougou, liebao, maxthon, bilibili |
shellVs | Shell version | string | (Optional) 20/... |
appleType | Apple device type | string | (Optional) ipad, iphone, ipod, iwatch |
Example: Determine the environment of the mobile QQ.
1const { system, shell } = getBrowserInfo(); 2const isMobileQQ = ["android", "ios"].includes(system) && ["qq_browser", "qq_app"].includes(shell);
isSafePWAEnv
Detect the margin of Safety. Determine if it is a secure PWA environment that it can run.
Usage:
1const ret = isSafePWAEnv(); 2console.log(ret);
Output:
1true
Web Performance
getPerformance
Get page load time(PerformanceNavigationTiming
).
This function uses the PerformanceNavigationTiming
API to get page load time data.
The PerformanceNavigationTiming
API provides more accurate and detailed information about page load time than the deprecated PerformanceTiming
API.
If you are using an older browser that does not support PerformanceNavigationTiming
, you can still use the PerformanceTiming
API by using the previous version of this library (v3.9.7
).
Usage:
1// `camelCase:false` (Default) Return underline(`a_b`) data. 2// `camelCase:true` Return hump(`aB`) data. 3getPerformance() 4 .then(res => { 5 console.log(JSON.stringify(res)); 6 }) 7 .catch(console.error);
Output:
1{"source":"PerformanceNavigationTiming","os":"others","os_version":"","device_type":"pc","network":"4g","screen_direction":"","unload_time":0,"redirect_time":0,"dns_time":0,"tcp_time":0,"ssl_time":0,"response_time":2,"download_time":2,"first_paint_time":288,"first_contentful_paint_time":288,"dom_ready_time":0,"onload_time":0,"white_time":0,"render_time":0,"decoded_body_size":718,"encoded_body_size":718}
Results:
Attribute | Description | Type | Values |
---|---|---|---|
dns_time | DNS Lookup | number | domainLookupEnd - domainLookupStart |
tcp_time | Connection Negotiation | number | connectEnd - connectStart |
response_time | Requests and Responses | number | responseStart - requestStart |
white_time | White Screen | number | responseStart - navigationStart |
dom_ready_time | Dom Ready | number | domContentLoadedEventStart - navigationStart |
onload_time | Onload | number | loadEventStart - navigationStart |
render_time | EventEnd | number | loadEventEnd -navigationStart |
unload_time | Unload | number | (Optional) unloadEventEnd - unloadEventStart |
redirect_time | Redirect | number | (Optional) redirectEnd - redirectStart |
ssl_time | SSL | number | (Optional) connectEnd - secureConnectionStart |
download_time | Download | number | (Optional) responseEnd - responseStart |
Debug
genCustomConsole
Custom console printing (console
).
Usage:
1const myConsole = genCustomConsole("MazeyLog:"); 2myConsole.log("I am string."); 3myConsole.info("I am boolean.", true); 4myConsole.info("I am number.", 123, 456); 5myConsole.info("I am object.", { a: 123, b: 456});
Output:
1MazeyLog: I am string. 2MazeyLog: I am boolean. true 3MazeyLog: I am number. 123 456 4MazeyLog: I am object. {a: 123, b: 456}
Contributing
Development Environment
Dependency | Version |
---|---|
Node.js | v16.19.0, v18.12.1 |
TypeScript | v5.1.6 |
Scripts
Install Dependencies:
1npm i
Development:
1npm run dev
Build:
1npm run build
Test:
1npm run test
Document:
1npm run docs
Returns
Values | Description | Type |
---|---|---|
ok | The operation was successful. | string |
loaded | Some assets have been loaded. | string |
fail | An error occurred. | string |
defined | The value is defined. | string |
undefined | The value is undefined. | string |
timeout | The operation timed out. | string |
true | The value is true. | boolean |
false | The value is false. | boolean |
License
This software is released under the terms of the MIT license.

No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
packaging workflow detected
Details
- Info: Project packages its releases by way of GitHub Actions.: .github/workflows/publish.yml:10
Reason
binaries present in source code
Details
- Warn: binary detected: scripts/convert/convert-markdown-to-typedoc-mac-darwin-amd64:1
- Warn: binary detected: scripts/convert/convert-typedoc-to-markdown-mac-darwin-amd64:1
Reason
8 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 7
Reason
Found 0/25 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/publish.yml:1
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Warn: no topLevel permission defined: .github/workflows/v3-publish.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:31: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/v3-publish.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/v3-publish.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/v3-publish.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/mazeyqian/mazey/v3-publish.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/publish.yml:20
- Warn: npmCommand not pinned by hash: .github/workflows/test.yml:27
- Warn: npmCommand not pinned by hash: .github/workflows/v3-publish.yml:19
- Info: 0 out of 8 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 3 npmCommand dependencies pinned
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
4.3
/10
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More