Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@curong/object

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@curong/object - npm Package Compare versions

Comparing version 0.0.0-alpha.3 to 0.0.0-alpha.4

40

dist/index.d.ts

@@ -155,2 +155,40 @@ /** 属性名的类型,属性名是 `string`、`number` 和 `symbol` 类型中的某一个类型。 */

export { ObjectType, PropertyKey, createWithNull, deleteAttrs, derive, isPrototypeProperty, shallowEqual };
/**
* 将一个值转换为一个字符串
*
* @param value 要转换的值
*
* @returns 返回一个字符串
* @throw 如果转换失败,则会抛出异常
* @example
*
* ```javascript
* const s = { value: '', number: 0, bool: false };
* const ret = await stringify(s);
* console.log(ret); // '{"value":"","number":0,"bool":false}'
* ```
*/
declare function stringify(value: any): Promise<string>;
/**
* 将一个对象中的键全部转换为小写,并返回一个新的对象
*
* @param object 要处理的对象
* @param isCover 当遇到重复对象名时是否覆盖之前的属性,默认为 `true`
*
* - 如果为 `true`,则会将新对象中之前所存储的属性中的值替换掉
* - 如果为 `false`,则不会对新对象中的属性重复赋值
*
* @returns 返回处理好的新的对象
* @example
*
* ```javascript
* let ret = toLowerCaseKey({ name: 1, NAME: 2 });
* console.log(ret); // { name: 2 }
* ret = toLowerCaseKey({ name: 1, NAME: 2 }, false);
* console.log(ret); // { name: 1 }
* ```
*/
declare function toLowerCaseKey(object: ObjectType, isCover?: boolean): ObjectType;
export { ObjectType, PropertyKey, createWithNull, deleteAttrs, derive, isPrototypeProperty, shallowEqual, stringify, toLowerCaseKey };

@@ -6,2 +6,5 @@ 'use strict';

require('stream');
var util = require('util');
require('process');
require('readline');

@@ -41,2 +44,6 @@ function isFunction(value) {

function isArray(value) {
return Array.isArray(value);
}
function isNull(value) {

@@ -50,2 +57,18 @@ return value === null;

function isArrayHave(value) {
return isArray(value) && value.length > 0;
}
function isNumberPrimitive(value) {
return typeof value === 'number';
}
function isNumberObject(value) {
return typeof value === 'object' && getTag(value) === 'Number';
}
function isNumber(value) {
return isNumberPrimitive(value) || isNumberObject(value);
}
function isObject(value) {

@@ -55,2 +78,41 @@ return getTag(value) === 'Object';

function isFalse(value) {
return value === false;
}
function isNaN(value) {
return Number.isNaN(value);
}
function isEqual(value, ...args) {
const handle = isNaN(value)
? (v) => isNaN(v)
: (v) => value === v;
if (isArrayHave(args)) {
for (let i = 0, len = args.length; i < len; i++) {
if (isFalse(handle(args[i]))) {
return false;
}
}
return true;
}
return false;
}
function isNotZero(value) {
return value !== 0;
}
function isObjectHave(value) {
return isObject(value) && Object.keys(value).length > 0;
}
function isStringHave(value) {
return isString(value) && value.length > 0;
}
function isSymbol(value) {
return typeof value === 'symbol';
}
function isTypeofObject(value) {

@@ -60,2 +122,10 @@ return typeof value === 'object' && !isNull(value);

function isUintSafe(value) {
return Number.isSafeInteger(value) && value >= 0;
}
function isZero(value) {
return value === 0;
}
function createWithNull(properties) {

@@ -125,2 +195,260 @@ if (isObject(properties)) {

function ansiFormat(options = {}) {
const setColor = [];
const resetColor = [];
const formatKeys = [
'bold',
'dim',
'italic',
'underlined',
'blink',
'rapidBlink',
'reverse',
'hidden',
'crossedOut'
];
for (let i = 0, len = formatKeys.length; i < len; i++) {
const key = formatKeys[i];
const value = options[key];
let resetAppend = 21;
if (isUndefined(value)) {
continue;
}
switch (key) {
case 'bold':
resetAppend++;
default:
if (isTrue(value)) {
setColor.push(i + 1);
resetColor.push(i + resetAppend);
}
else if (isFalse(value)) {
resetColor.push(i + resetAppend);
}
break;
}
}
return {
set: setColor.join(';'),
reset: resetColor.join(';')
};
}
function colorCode8bit(colorCode) {
if (!isUintSafe(colorCode) || colorCode < 0 || colorCode > 255) {
throw new TypeError(`[colorCode8bit]: colorCode不是一个有效数字, "${colorCode}"`);
}
return {
foreground: `38;5;${colorCode}`,
background: `48;5;${colorCode}`
};
}
const COLORS_CODE = {
standard: [
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
],
highIntensity: [
'lightblack',
'lightred',
'lightgreen',
'lightyellow',
'lightblue',
'lightmagenta',
'lightcyan',
'lightwhite'
]
};
function colorNameCode8bit(colorName) {
const colors = COLORS_CODE.standard.concat(COLORS_CODE.highIntensity);
return colorCode8bit(colors.findIndex(color => color === colorName));
}
const ESC = '\u001B';
const CSI = ESC + '[';
function fontColor(value, options) {
if (isZero(value.length)) {
return '';
}
if (isUndefined(options)) {
return `${CSI}0m${value}`;
}
const setCodes = [];
const resetCodes = [];
const { foreground, background } = options;
if (foreground) {
setCodes.push(colorNameCode8bit(foreground).foreground);
resetCodes.push('39');
}
if (background) {
setCodes.push(colorNameCode8bit(background).background);
resetCodes.push('49');
}
const { set, reset } = ansiFormat(options);
set.length > 0 && setCodes.push(set);
reset.length > 0 && resetCodes.push(reset);
const left = `${CSI}${setCodes.join(';')}m`;
const right = `${CSI}${resetCodes.join(';')}m`;
return left + value + right;
}
const LF = '\n';
function makeTitle(type = 'error', title) {
if (!isStringHave(title)) {
return '';
}
const createStyleText = (color) => {
const leftTitle = fontColor(` ${type.toLocaleUpperCase()} `, {
foreground: 'lightwhite',
background: color
});
const rightContent = fontColor(title, { foreground: color });
return [leftTitle, rightContent].join(' ');
};
switch (type) {
case 'warn':
return createStyleText('yellow');
case 'info':
return createStyleText('green');
case 'error':
default:
return createStyleText('lightred');
}
}
function makeInfo(info) {
const messages = [];
if (!isObjectHave(info)) {
return messages;
}
const { type = 'error', name, code, message, data, date = true, stack = false } = info;
const INFO_NAME = {
DATE: '时间',
NAME: '名称',
CODE: '代码',
MESSAGE: '消息',
DATA: '数据',
STACK: '堆栈'
};
const pushLittleTitle = (data, name) => {
if (isStringHave(name)) {
const title = fontColor(` ${name} `, {
foreground: 'lightwhite',
background: 'cyan'
});
messages.push(LF + title);
}
messages.push(data);
};
Object.keys(info).forEach(key => {
switch (key) {
case 'name':
if (isStringHave(name)) {
pushLittleTitle(name, INFO_NAME.NAME);
}
break;
case 'code':
if (isNumber(code) || isStringHave(code)) {
pushLittleTitle(code, INFO_NAME.CODE);
}
break;
case 'message':
if (isStringHave(message)) {
pushLittleTitle(message, INFO_NAME.MESSAGE);
}
break;
case 'data':
pushLittleTitle(data, INFO_NAME.DATA);
break;
}
});
if (date) {
const time = new Date().toLocaleString();
pushLittleTitle(fontColor(time, { foreground: 'magenta' }), INFO_NAME.DATE);
}
if (stack || (isEqual(type, 'error') && messages.length > 0)) {
const stack = new Error().stack;
if (isStringHave(stack)) {
const newStack = LF + stack.split(LF).slice(3).join(LF);
const styleText = fontColor(newStack, {
foreground: 'red'
});
pushLittleTitle(styleText, INFO_NAME.STACK);
}
}
return messages;
}
function format(info, options) {
options = {
showHidden: true,
depth: null,
colors: true,
maxArrayLength: null,
compact: false,
sorted: true,
...options
};
const { dividers = true, title = true } = options.display || {};
const splitChars = '-'.repeat(80);
const styleText = [];
const styleMsg = makeInfo(info);
if (title) {
styleText.push(makeTitle(info.type, info.title));
}
if (dividers) {
styleText.push(LF + splitChars, ...styleMsg, LF + splitChars);
}
else {
styleText.push(...styleMsg);
}
if (isNotZero(styleMsg.length)) {
styleText[0] = LF + styleText[0].trimStart();
styleText.push(LF);
}
return util.formatWithOptions({ ...options }, ...styleText);
}
function stringify(value) {
return new Promise(resolve => {
try {
resolve(JSON.stringify(value));
}
catch (error) {
throw format({
name: 'stringify',
message: '转换字符串失败',
data: { value, error }
});
}
});
}
function toLowerCaseKey(object, isCover = true) {
const set = new Set();
return Reflect.ownKeys(object).reduce((memo, key) => {
const value = object[key];
if (isSymbol(key) || isNumber(key)) {
memo[key] = value;
return memo;
}
key = key.toLocaleLowerCase();
if (isCover) {
memo[key] = value;
}
else if (!set.has(key)) {
memo[key] = value;
set.add(key);
}
return memo;
}, {});
}
exports.createWithNull = createWithNull;

@@ -131,1 +459,3 @@ exports.deleteAttrs = deleteAttrs;

exports.shallowEqual = shallowEqual;
exports.stringify = stringify;
exports.toLowerCaseKey = toLowerCaseKey;
import 'stream';
import { formatWithOptions } from 'util';
import 'process';
import 'readline';
function isFunction(value) {
function isFunction$1(value) {
return typeof value === 'function';
}
function isStringPrimitive(value) {
function isStringPrimitive$1(value) {
return typeof value === 'string';
}
function isStringObject(value) {
return typeof value === 'object' && getTag(value) === 'String';
function isStringObject$1(value) {
return typeof value === 'object' && getTag$1(value) === 'String';
}
function isString(value) {
return isStringPrimitive(value) || isStringObject(value);
function isString$1(value) {
return isStringPrimitive$1(value) || isStringObject$1(value);
}
function isTrue(value) {
function isTrue$1(value) {
return value === true;
}
function getTag(value, slice = true) {
function getTag$1(value, slice = true) {
const toTag = Object.prototype.toString;
let toStringTag = null;
if (!isFunction(toTag) || !isString((toStringTag = toTag.call(value)))) {
if (!isFunction$1(toTag) || !isString$1((toStringTag = toTag.call(value)))) {
return toStringTag;
}
return isTrue(slice) &&
return isTrue$1(slice) &&
toStringTag.startsWith('[object ') &&

@@ -40,10 +43,26 @@ toStringTag.endsWith(']')

function isUndefined(value) {
function isUndefined$1(value) {
return typeof value === 'undefined';
}
function isObject(value) {
return getTag(value) === 'Object';
function isNumberPrimitive$1(value) {
return typeof value === 'number';
}
function isNumberObject$1(value) {
return typeof value === 'object' && getTag$1(value) === 'Number';
}
function isNumber$1(value) {
return isNumberPrimitive$1(value) || isNumberObject$1(value);
}
function isObject$1(value) {
return getTag$1(value) === 'Object';
}
function isSymbol(value) {
return typeof value === 'symbol';
}
function isTypeofObject(value) {

@@ -54,3 +73,3 @@ return typeof value === 'object' && !isNull(value);

function createWithNull(properties) {
if (isObject(properties)) {
if (isObject$1(properties)) {
return Object.create(null, properties);

@@ -66,3 +85,3 @@ }

let key;
while (!isUndefined((key = objKeys.shift()))) {
while (!isUndefined$1((key = objKeys.shift()))) {
if (!keysSet.has(key)) {

@@ -77,3 +96,3 @@ Object.defineProperty(ret, key, Object.getOwnPropertyDescriptor(obj, key));

let key;
while (!isUndefined((key = deleteKeys.pop()))) {
while (!isUndefined$1((key = deleteKeys.pop()))) {
if (!Reflect.deleteProperty(obj, key)) {

@@ -120,2 +139,364 @@ deleteKeys.push(key);

export { createWithNull, deleteAttrs, derive, isPrototypeProperty, shallowEqual };
function isFunction(value) {
return typeof value === 'function';
}
function isStringPrimitive(value) {
return typeof value === 'string';
}
function isStringObject(value) {
return typeof value === 'object' && getTag(value) === 'String';
}
function isString(value) {
return isStringPrimitive(value) || isStringObject(value);
}
function isTrue(value) {
return value === true;
}
function getTag(value, slice = true) {
const toTag = Object.prototype.toString;
let toStringTag = null;
if (!isFunction(toTag) || !isString((toStringTag = toTag.call(value)))) {
return toStringTag;
}
return isTrue(slice) &&
toStringTag.startsWith('[object ') &&
toStringTag.endsWith(']')
? toStringTag.slice(8, -1)
: toStringTag;
}
function isArray(value) {
return Array.isArray(value);
}
function isUndefined(value) {
return typeof value === 'undefined';
}
function isArrayHave(value) {
return isArray(value) && value.length > 0;
}
function isNumberPrimitive(value) {
return typeof value === 'number';
}
function isNumberObject(value) {
return typeof value === 'object' && getTag(value) === 'Number';
}
function isNumber(value) {
return isNumberPrimitive(value) || isNumberObject(value);
}
function isObject(value) {
return getTag(value) === 'Object';
}
function isFalse(value) {
return value === false;
}
function isNaN$1(value) {
return Number.isNaN(value);
}
function isEqual(value, ...args) {
const handle = isNaN$1(value)
? (v) => isNaN$1(v)
: (v) => value === v;
if (isArrayHave(args)) {
for (let i = 0, len = args.length; i < len; i++) {
if (isFalse(handle(args[i]))) {
return false;
}
}
return true;
}
return false;
}
function isNotZero(value) {
return value !== 0;
}
function isObjectHave(value) {
return isObject(value) && Object.keys(value).length > 0;
}
function isStringHave(value) {
return isString(value) && value.length > 0;
}
function isUintSafe(value) {
return Number.isSafeInteger(value) && value >= 0;
}
function isZero(value) {
return value === 0;
}
function ansiFormat(options = {}) {
const setColor = [];
const resetColor = [];
const formatKeys = [
'bold',
'dim',
'italic',
'underlined',
'blink',
'rapidBlink',
'reverse',
'hidden',
'crossedOut'
];
for (let i = 0, len = formatKeys.length; i < len; i++) {
const key = formatKeys[i];
const value = options[key];
let resetAppend = 21;
if (isUndefined(value)) {
continue;
}
switch (key) {
case 'bold':
resetAppend++;
default:
if (isTrue(value)) {
setColor.push(i + 1);
resetColor.push(i + resetAppend);
}
else if (isFalse(value)) {
resetColor.push(i + resetAppend);
}
break;
}
}
return {
set: setColor.join(';'),
reset: resetColor.join(';')
};
}
function colorCode8bit(colorCode) {
if (!isUintSafe(colorCode) || colorCode < 0 || colorCode > 255) {
throw new TypeError(`[colorCode8bit]: colorCode不是一个有效数字, "${colorCode}"`);
}
return {
foreground: `38;5;${colorCode}`,
background: `48;5;${colorCode}`
};
}
const COLORS_CODE = {
standard: [
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
],
highIntensity: [
'lightblack',
'lightred',
'lightgreen',
'lightyellow',
'lightblue',
'lightmagenta',
'lightcyan',
'lightwhite'
]
};
function colorNameCode8bit(colorName) {
const colors = COLORS_CODE.standard.concat(COLORS_CODE.highIntensity);
return colorCode8bit(colors.findIndex(color => color === colorName));
}
const ESC = '\u001B';
const CSI = ESC + '[';
function fontColor(value, options) {
if (isZero(value.length)) {
return '';
}
if (isUndefined(options)) {
return `${CSI}0m${value}`;
}
const setCodes = [];
const resetCodes = [];
const { foreground, background } = options;
if (foreground) {
setCodes.push(colorNameCode8bit(foreground).foreground);
resetCodes.push('39');
}
if (background) {
setCodes.push(colorNameCode8bit(background).background);
resetCodes.push('49');
}
const { set, reset } = ansiFormat(options);
set.length > 0 && setCodes.push(set);
reset.length > 0 && resetCodes.push(reset);
const left = `${CSI}${setCodes.join(';')}m`;
const right = `${CSI}${resetCodes.join(';')}m`;
return left + value + right;
}
const LF = '\n';
function makeTitle(type = 'error', title) {
if (!isStringHave(title)) {
return '';
}
const createStyleText = (color) => {
const leftTitle = fontColor(` ${type.toLocaleUpperCase()} `, {
foreground: 'lightwhite',
background: color
});
const rightContent = fontColor(title, { foreground: color });
return [leftTitle, rightContent].join(' ');
};
switch (type) {
case 'warn':
return createStyleText('yellow');
case 'info':
return createStyleText('green');
case 'error':
default:
return createStyleText('lightred');
}
}
function makeInfo(info) {
const messages = [];
if (!isObjectHave(info)) {
return messages;
}
const { type = 'error', name, code, message, data, date = true, stack = false } = info;
const INFO_NAME = {
DATE: '时间',
NAME: '名称',
CODE: '代码',
MESSAGE: '消息',
DATA: '数据',
STACK: '堆栈'
};
const pushLittleTitle = (data, name) => {
if (isStringHave(name)) {
const title = fontColor(` ${name} `, {
foreground: 'lightwhite',
background: 'cyan'
});
messages.push(LF + title);
}
messages.push(data);
};
Object.keys(info).forEach(key => {
switch (key) {
case 'name':
if (isStringHave(name)) {
pushLittleTitle(name, INFO_NAME.NAME);
}
break;
case 'code':
if (isNumber(code) || isStringHave(code)) {
pushLittleTitle(code, INFO_NAME.CODE);
}
break;
case 'message':
if (isStringHave(message)) {
pushLittleTitle(message, INFO_NAME.MESSAGE);
}
break;
case 'data':
pushLittleTitle(data, INFO_NAME.DATA);
break;
}
});
if (date) {
const time = new Date().toLocaleString();
pushLittleTitle(fontColor(time, { foreground: 'magenta' }), INFO_NAME.DATE);
}
if (stack || (isEqual(type, 'error') && messages.length > 0)) {
const stack = new Error().stack;
if (isStringHave(stack)) {
const newStack = LF + stack.split(LF).slice(3).join(LF);
const styleText = fontColor(newStack, {
foreground: 'red'
});
pushLittleTitle(styleText, INFO_NAME.STACK);
}
}
return messages;
}
function format(info, options) {
options = {
showHidden: true,
depth: null,
colors: true,
maxArrayLength: null,
compact: false,
sorted: true,
...options
};
const { dividers = true, title = true } = options.display || {};
const splitChars = '-'.repeat(80);
const styleText = [];
const styleMsg = makeInfo(info);
if (title) {
styleText.push(makeTitle(info.type, info.title));
}
if (dividers) {
styleText.push(LF + splitChars, ...styleMsg, LF + splitChars);
}
else {
styleText.push(...styleMsg);
}
if (isNotZero(styleMsg.length)) {
styleText[0] = LF + styleText[0].trimStart();
styleText.push(LF);
}
return formatWithOptions({ ...options }, ...styleText);
}
function stringify(value) {
return new Promise(resolve => {
try {
resolve(JSON.stringify(value));
}
catch (error) {
throw format({
name: 'stringify',
message: '转换字符串失败',
data: { value, error }
});
}
});
}
function toLowerCaseKey(object, isCover = true) {
const set = new Set();
return Reflect.ownKeys(object).reduce((memo, key) => {
const value = object[key];
if (isSymbol(key) || isNumber$1(key)) {
memo[key] = value;
return memo;
}
key = key.toLocaleLowerCase();
if (isCover) {
memo[key] = value;
}
else if (!set.has(key)) {
memo[key] = value;
set.add(key);
}
return memo;
}, {});
}
export { createWithNull, deleteAttrs, derive, isPrototypeProperty, shallowEqual, stringify, toLowerCaseKey };

2

dist/index.prod.js

@@ -1,1 +0,1 @@

"use strict";function t(t){return function(t){return"string"==typeof t}(t)||function(t){return"object"==typeof t&&"String"===e(t)}(t)}function e(e,r=!0){const n=Object.prototype.toString;let o=null;return function(t){return"function"==typeof t}(n)&&t(o=n.call(e))&&function(t){return!0===t}(r)&&o.startsWith("[object ")&&o.endsWith("]")?o.slice(8,-1):o}function r(t){return void 0===t}function n(t,e){const n=Object.create(Object.getPrototypeOf(t)),o=new Set(e),c=Reflect.ownKeys(t);let u;for(;!r(u=c.shift());)o.has(u)||Object.defineProperty(n,u,Object.getOwnPropertyDescriptor(t,u));return n}Object.defineProperty(exports,"__esModule",{value:!0}),require("stream");const o="function"==typeof Object.is?Object.is:(t,e)=>t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e,c=Object.prototype.hasOwnProperty;exports.createWithNull=function(t){return"Object"===e(t)?Object.create(null,t):Object.create(null)},exports.deleteAttrs=function(t,e){let o;for(;!r(o=e.pop());)if(!Reflect.deleteProperty(t,o))return e.push(o),n(t,e);return t},exports.derive=n,exports.isPrototypeProperty=function(t,e){return"object"==typeof(r=t)&&!function(t){return null===t}(r)&&!t.hasOwnProperty(e)&&e in t;var r},exports.shallowEqual=function(t,e){if(o(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;const r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let n=0;n<r.length;n++)if(!c.call(e,r[n])||!o(t[r[n]],e[r[n]]))return!1;return!0};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("stream");var e=require("util");function t(e){return function(e){return"string"==typeof e}(e)||function(e){return"object"==typeof e&&"String"===n(e)}(e)}function r(e){return!0===e}function n(e,n=!0){const o=Object.prototype.toString;let u=null;return function(e){return"function"==typeof e}(o)&&t(u=o.call(e))&&r(n)&&u.startsWith("[object ")&&u.endsWith("]")?u.slice(8,-1):u}function o(e){return void 0===e}function u(e){return function(e){return Array.isArray(e)}(e)&&e.length>0}function i(e){return function(e){return"number"==typeof e}(e)||function(e){return"object"==typeof e&&"Number"===n(e)}(e)}function c(e){return"Object"===n(e)}function s(e){return!1===e}function l(e){return Number.isNaN(e)}function a(e){return t(e)&&e.length>0}function f(e,t){const r=Object.create(Object.getPrototypeOf(e)),n=new Set(t),u=Reflect.ownKeys(e);let i;for(;!o(i=u.shift());)n.has(i)||Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(e,i));return r}require("process"),require("readline");const h="function"==typeof Object.is?Object.is:(e,t)=>e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t,p=Object.prototype.hasOwnProperty;function d(e){if(t=e,!(Number.isSafeInteger(t)&&t>=0)||e<0||e>255)throw new TypeError(`[colorCode8bit]: colorCode不是一个有效数字, "${e}"`);var t;return{foreground:"38;5;"+e,background:"48;5;"+e}}const g={standard:["black","red","green","yellow","blue","magenta","cyan","white"],highIntensity:["lightblack","lightred","lightgreen","lightyellow","lightblue","lightmagenta","lightcyan","lightwhite"]};function y(e){return d(g.standard.concat(g.highIntensity).findIndex(t=>t===e))}function b(e,t){if(function(e){return 0===e}(e.length))return"";if(o(t))return""+e;const n=[],u=[],{foreground:i,background:c}=t;i&&(n.push(y(i).foreground),u.push("39")),c&&(n.push(y(c).background),u.push("49"));const{set:l,reset:a}=function(e={}){const t=[],n=[],u=["bold","dim","italic","underlined","blink","rapidBlink","reverse","hidden","crossedOut"];for(let i=0,c=u.length;i<c;i++){const c=u[i],l=e[c];let a=21;if(!o(l))switch(c){case"bold":a++;default:r(l)?(t.push(i+1),n.push(i+a)):s(l)&&n.push(i+a)}}return{set:t.join(";"),reset:n.join(";")}}(t);return l.length>0&&n.push(l),a.length>0&&u.push(a),`[${n.join(";")}m`+e+`[${u.join(";")}m`}const j="\n";function w(e){const t=[];if(!(c(r=e)&&Object.keys(r).length>0))return t;var r;const{type:n="error",name:o,code:f,message:h,data:p,date:d=!0,stack:g=!1}=e,y="时间",w="名称",m="代码",O="消息",k="数据",v="堆栈",x=(e,r)=>{if(a(r)){const e=b(` ${r} `,{foreground:"lightwhite",background:"cyan"});t.push(j+e)}t.push(e)};if(Object.keys(e).forEach(e=>{switch(e){case"name":a(o)&&x(o,w);break;case"code":(i(f)||a(f))&&x(f,m);break;case"message":a(h)&&x(h,O);break;case"data":x(p,k)}}),d){const e=(new Date).toLocaleString();x(b(e,{foreground:"magenta"}),y)}if(g||function(e,...t){const r=l(e)?e=>l(e):t=>e===t;if(u(t)){for(let e=0,n=t.length;e<n;e++)if(s(r(t[e])))return!1;return!0}return!1}(n,"error")&&t.length>0){const e=(new Error).stack;if(a(e)){const t=b(j+e.split(j).slice(3).join(j),{foreground:"red"});x(t,v)}}return t}function m(t,r){r={showHidden:!0,depth:null,colors:!0,maxArrayLength:null,compact:!1,sorted:!0,...r};const{dividers:n=!0,title:o=!0}=r.display||{},u="-".repeat(80),i=[],c=w(t);return o&&i.push(function(e="error",t){if(!a(t))return"";const r=r=>[b(` ${e.toLocaleUpperCase()} `,{foreground:"lightwhite",background:r}),b(t,{foreground:r})].join(" ");switch(e){case"warn":return r("yellow");case"info":return r("green");case"error":default:return r("lightred")}}(t.type,t.title)),n?i.push(j+u,...c,j+u):i.push(...c),0!==c.length&&(i[0]=j+i[0].trimStart(),i.push(j)),e.formatWithOptions({...r},...i)}exports.createWithNull=function(e){return c(e)?Object.create(null,e):Object.create(null)},exports.deleteAttrs=function(e,t){let r;for(;!o(r=t.pop());)if(!Reflect.deleteProperty(e,r))return t.push(r),f(e,t);return e},exports.derive=f,exports.isPrototypeProperty=function(e,t){return"object"==typeof(r=e)&&!function(e){return null===e}(r)&&!e.hasOwnProperty(t)&&t in e;var r},exports.shallowEqual=function(e,t){if(h(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let n=0;n<r.length;n++)if(!p.call(t,r[n])||!h(e[r[n]],t[r[n]]))return!1;return!0},exports.stringify=function(e){return new Promise(t=>{try{t(JSON.stringify(e))}catch(t){throw m({name:"stringify",message:"转换字符串失败",data:{value:e,error:t}})}})},exports.toLowerCaseKey=function(e,t=!0){const r=new Set;return Reflect.ownKeys(e).reduce((n,o)=>{const u=e[o];return function(e){return"symbol"==typeof e}(o)||i(o)?(n[o]=u,n):(o=o.toLocaleLowerCase(),t?n[o]=u:r.has(o)||(n[o]=u,r.add(o)),n)},{})};
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('stream')) :
typeof define === 'function' && define.amd ? define(['exports', 'stream'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.object = {}));
}(this, (function (exports) { 'use strict';
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('stream'), require('util'), require('process'), require('readline')) :
typeof define === 'function' && define.amd ? define(['exports', 'stream', 'util', 'process', 'readline'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.object = {}, null, global.util));
}(this, (function (exports, stream, util) { 'use strict';

@@ -40,2 +40,6 @@ function isFunction(value) {

function isArray(value) {
return Array.isArray(value);
}
function isNull(value) {

@@ -49,2 +53,18 @@ return value === null;

function isArrayHave(value) {
return isArray(value) && value.length > 0;
}
function isNumberPrimitive(value) {
return typeof value === 'number';
}
function isNumberObject(value) {
return typeof value === 'object' && getTag(value) === 'Number';
}
function isNumber(value) {
return isNumberPrimitive(value) || isNumberObject(value);
}
function isObject(value) {

@@ -54,2 +74,41 @@ return getTag(value) === 'Object';

function isFalse(value) {
return value === false;
}
function isNaN(value) {
return Number.isNaN(value);
}
function isEqual(value, ...args) {
const handle = isNaN(value)
? (v) => isNaN(v)
: (v) => value === v;
if (isArrayHave(args)) {
for (let i = 0, len = args.length; i < len; i++) {
if (isFalse(handle(args[i]))) {
return false;
}
}
return true;
}
return false;
}
function isNotZero(value) {
return value !== 0;
}
function isObjectHave(value) {
return isObject(value) && Object.keys(value).length > 0;
}
function isStringHave(value) {
return isString(value) && value.length > 0;
}
function isSymbol(value) {
return typeof value === 'symbol';
}
function isTypeofObject(value) {

@@ -59,2 +118,10 @@ return typeof value === 'object' && !isNull(value);

function isUintSafe(value) {
return Number.isSafeInteger(value) && value >= 0;
}
function isZero(value) {
return value === 0;
}
function createWithNull(properties) {

@@ -124,2 +191,260 @@ if (isObject(properties)) {

function ansiFormat(options = {}) {
const setColor = [];
const resetColor = [];
const formatKeys = [
'bold',
'dim',
'italic',
'underlined',
'blink',
'rapidBlink',
'reverse',
'hidden',
'crossedOut'
];
for (let i = 0, len = formatKeys.length; i < len; i++) {
const key = formatKeys[i];
const value = options[key];
let resetAppend = 21;
if (isUndefined(value)) {
continue;
}
switch (key) {
case 'bold':
resetAppend++;
default:
if (isTrue(value)) {
setColor.push(i + 1);
resetColor.push(i + resetAppend);
}
else if (isFalse(value)) {
resetColor.push(i + resetAppend);
}
break;
}
}
return {
set: setColor.join(';'),
reset: resetColor.join(';')
};
}
function colorCode8bit(colorCode) {
if (!isUintSafe(colorCode) || colorCode < 0 || colorCode > 255) {
throw new TypeError(`[colorCode8bit]: colorCode不是一个有效数字, "${colorCode}"`);
}
return {
foreground: `38;5;${colorCode}`,
background: `48;5;${colorCode}`
};
}
const COLORS_CODE = {
standard: [
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
],
highIntensity: [
'lightblack',
'lightred',
'lightgreen',
'lightyellow',
'lightblue',
'lightmagenta',
'lightcyan',
'lightwhite'
]
};
function colorNameCode8bit(colorName) {
const colors = COLORS_CODE.standard.concat(COLORS_CODE.highIntensity);
return colorCode8bit(colors.findIndex(color => color === colorName));
}
const ESC = '\u001B';
const CSI = ESC + '[';
function fontColor(value, options) {
if (isZero(value.length)) {
return '';
}
if (isUndefined(options)) {
return `${CSI}0m${value}`;
}
const setCodes = [];
const resetCodes = [];
const { foreground, background } = options;
if (foreground) {
setCodes.push(colorNameCode8bit(foreground).foreground);
resetCodes.push('39');
}
if (background) {
setCodes.push(colorNameCode8bit(background).background);
resetCodes.push('49');
}
const { set, reset } = ansiFormat(options);
set.length > 0 && setCodes.push(set);
reset.length > 0 && resetCodes.push(reset);
const left = `${CSI}${setCodes.join(';')}m`;
const right = `${CSI}${resetCodes.join(';')}m`;
return left + value + right;
}
const LF = '\n';
function makeTitle(type = 'error', title) {
if (!isStringHave(title)) {
return '';
}
const createStyleText = (color) => {
const leftTitle = fontColor(` ${type.toLocaleUpperCase()} `, {
foreground: 'lightwhite',
background: color
});
const rightContent = fontColor(title, { foreground: color });
return [leftTitle, rightContent].join(' ');
};
switch (type) {
case 'warn':
return createStyleText('yellow');
case 'info':
return createStyleText('green');
case 'error':
default:
return createStyleText('lightred');
}
}
function makeInfo(info) {
const messages = [];
if (!isObjectHave(info)) {
return messages;
}
const { type = 'error', name, code, message, data, date = true, stack = false } = info;
const INFO_NAME = {
DATE: '时间',
NAME: '名称',
CODE: '代码',
MESSAGE: '消息',
DATA: '数据',
STACK: '堆栈'
};
const pushLittleTitle = (data, name) => {
if (isStringHave(name)) {
const title = fontColor(` ${name} `, {
foreground: 'lightwhite',
background: 'cyan'
});
messages.push(LF + title);
}
messages.push(data);
};
Object.keys(info).forEach(key => {
switch (key) {
case 'name':
if (isStringHave(name)) {
pushLittleTitle(name, INFO_NAME.NAME);
}
break;
case 'code':
if (isNumber(code) || isStringHave(code)) {
pushLittleTitle(code, INFO_NAME.CODE);
}
break;
case 'message':
if (isStringHave(message)) {
pushLittleTitle(message, INFO_NAME.MESSAGE);
}
break;
case 'data':
pushLittleTitle(data, INFO_NAME.DATA);
break;
}
});
if (date) {
const time = new Date().toLocaleString();
pushLittleTitle(fontColor(time, { foreground: 'magenta' }), INFO_NAME.DATE);
}
if (stack || (isEqual(type, 'error') && messages.length > 0)) {
const stack = new Error().stack;
if (isStringHave(stack)) {
const newStack = LF + stack.split(LF).slice(3).join(LF);
const styleText = fontColor(newStack, {
foreground: 'red'
});
pushLittleTitle(styleText, INFO_NAME.STACK);
}
}
return messages;
}
function format(info, options) {
options = {
showHidden: true,
depth: null,
colors: true,
maxArrayLength: null,
compact: false,
sorted: true,
...options
};
const { dividers = true, title = true } = options.display || {};
const splitChars = '-'.repeat(80);
const styleText = [];
const styleMsg = makeInfo(info);
if (title) {
styleText.push(makeTitle(info.type, info.title));
}
if (dividers) {
styleText.push(LF + splitChars, ...styleMsg, LF + splitChars);
}
else {
styleText.push(...styleMsg);
}
if (isNotZero(styleMsg.length)) {
styleText[0] = LF + styleText[0].trimStart();
styleText.push(LF);
}
return util.formatWithOptions({ ...options }, ...styleText);
}
function stringify(value) {
return new Promise(resolve => {
try {
resolve(JSON.stringify(value));
}
catch (error) {
throw format({
name: 'stringify',
message: '转换字符串失败',
data: { value, error }
});
}
});
}
function toLowerCaseKey(object, isCover = true) {
const set = new Set();
return Reflect.ownKeys(object).reduce((memo, key) => {
const value = object[key];
if (isSymbol(key) || isNumber(key)) {
memo[key] = value;
return memo;
}
key = key.toLocaleLowerCase();
if (isCover) {
memo[key] = value;
}
else if (!set.has(key)) {
memo[key] = value;
set.add(key);
}
return memo;
}, {});
}
exports.createWithNull = createWithNull;

@@ -130,2 +455,4 @@ exports.deleteAttrs = deleteAttrs;

exports.shallowEqual = shallowEqual;
exports.stringify = stringify;
exports.toLowerCaseKey = toLowerCaseKey;

@@ -132,0 +459,0 @@ Object.defineProperty(exports, '__esModule', { value: true });

@@ -1,1 +0,1 @@

!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("stream")):"function"==typeof define&&define.amd?define(["exports","stream"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).object={})}(this,(function(t){"use strict";function e(t){return function(t){return"string"==typeof t}(t)||function(t){return"object"==typeof t&&"String"===n(t)}(t)}function n(t,n=!0){const r=Object.prototype.toString;let o=null;return function(t){return"function"==typeof t}(r)&&e(o=r.call(t))&&function(t){return!0===t}(n)&&o.startsWith("[object ")&&o.endsWith("]")?o.slice(8,-1):o}function r(t){return void 0===t}function o(t,e){const n=Object.create(Object.getPrototypeOf(t)),o=new Set(e),c=Reflect.ownKeys(t);let u;for(;!r(u=c.shift());)o.has(u)||Object.defineProperty(n,u,Object.getOwnPropertyDescriptor(t,u));return n}const c="function"==typeof Object.is?Object.is:(t,e)=>t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e,u=Object.prototype.hasOwnProperty;t.createWithNull=function(t){return"Object"===n(t)?Object.create(null,t):Object.create(null)},t.deleteAttrs=function(t,e){let n;for(;!r(n=e.pop());)if(!Reflect.deleteProperty(t,n))return e.push(n),o(t,e);return t},t.derive=o,t.isPrototypeProperty=function(t,e){return"object"==typeof(n=t)&&!function(t){return null===t}(n)&&!t.hasOwnProperty(e)&&e in t;var n},t.shallowEqual=function(t,e){if(c(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(let r=0;r<n.length;r++)if(!u.call(e,n[r])||!c(t[n[r]],e[n[r]]))return!1;return!0},Object.defineProperty(t,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("stream"),require("util"),require("process"),require("readline")):"function"==typeof define&&define.amd?define(["exports","stream","util","process","readline"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).object={},null,e.util)}(this,(function(e,t,n){"use strict";function r(e){return function(e){return"string"==typeof e}(e)||function(e){return"object"==typeof e&&"String"===i(e)}(e)}function o(e){return!0===e}function i(e,t=!0){const n=Object.prototype.toString;let i=null;return function(e){return"function"==typeof e}(n)&&r(i=n.call(e))&&o(t)&&i.startsWith("[object ")&&i.endsWith("]")?i.slice(8,-1):i}function u(e){return void 0===e}function c(e){return function(e){return Array.isArray(e)}(e)&&e.length>0}function s(e){return function(e){return"number"==typeof e}(e)||function(e){return"object"==typeof e&&"Number"===i(e)}(e)}function l(e){return"Object"===i(e)}function f(e){return!1===e}function a(e){return Number.isNaN(e)}function h(e){return r(e)&&e.length>0}function d(e,t){const n=Object.create(Object.getPrototypeOf(e)),r=new Set(t),o=Reflect.ownKeys(e);let i;for(;!u(i=o.shift());)r.has(i)||Object.defineProperty(n,i,Object.getOwnPropertyDescriptor(e,i));return n}const p="function"==typeof Object.is?Object.is:(e,t)=>e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t,g=Object.prototype.hasOwnProperty;function y(e){if(t=e,!(Number.isSafeInteger(t)&&t>=0)||e<0||e>255)throw new TypeError(`[colorCode8bit]: colorCode不是一个有效数字, "${e}"`);var t;return{foreground:"38;5;"+e,background:"48;5;"+e}}const b={standard:["black","red","green","yellow","blue","magenta","cyan","white"],highIntensity:["lightblack","lightred","lightgreen","lightyellow","lightblue","lightmagenta","lightcyan","lightwhite"]};function j(e){return y(b.standard.concat(b.highIntensity).findIndex(t=>t===e))}function w(e,t){if(function(e){return 0===e}(e.length))return"";if(u(t))return""+e;const n=[],r=[],{foreground:i,background:c}=t;i&&(n.push(j(i).foreground),r.push("39")),c&&(n.push(j(c).background),r.push("49"));const{set:s,reset:l}=function(e={}){const t=[],n=[],r=["bold","dim","italic","underlined","blink","rapidBlink","reverse","hidden","crossedOut"];for(let i=0,c=r.length;i<c;i++){const c=r[i],s=e[c];let l=21;if(!u(s))switch(c){case"bold":l++;default:o(s)?(t.push(i+1),n.push(i+l)):f(s)&&n.push(i+l)}}return{set:t.join(";"),reset:n.join(";")}}(t);return s.length>0&&n.push(s),l.length>0&&r.push(l),`[${n.join(";")}m`+e+`[${r.join(";")}m`}const m="\n";function O(e){const t=[];if(!(l(n=e)&&Object.keys(n).length>0))return t;var n;const{type:r="error",name:o,code:i,message:u,data:d,date:p=!0,stack:g=!1}=e,y="时间",b="名称",j="代码",O="消息",k="数据",P="堆栈",v=(e,n)=>{if(h(n)){const e=w(` ${n} `,{foreground:"lightwhite",background:"cyan"});t.push(m+e)}t.push(e)};if(Object.keys(e).forEach(e=>{switch(e){case"name":h(o)&&v(o,b);break;case"code":(s(i)||h(i))&&v(i,j);break;case"message":h(u)&&v(u,O);break;case"data":v(d,k)}}),p){const e=(new Date).toLocaleString();v(w(e,{foreground:"magenta"}),y)}if(g||function(e,...t){const n=a(e)?e=>a(e):t=>e===t;if(c(t)){for(let e=0,r=t.length;e<r;e++)if(f(n(t[e])))return!1;return!0}return!1}(r,"error")&&t.length>0){const e=(new Error).stack;if(h(e)){const t=w(m+e.split(m).slice(3).join(m),{foreground:"red"});v(t,P)}}return t}function k(e,t){t={showHidden:!0,depth:null,colors:!0,maxArrayLength:null,compact:!1,sorted:!0,...t};const{dividers:r=!0,title:o=!0}=t.display||{},i="-".repeat(80),u=[],c=O(e);return o&&u.push(function(e="error",t){if(!h(t))return"";const n=n=>[w(` ${e.toLocaleUpperCase()} `,{foreground:"lightwhite",background:n}),w(t,{foreground:n})].join(" ");switch(e){case"warn":return n("yellow");case"info":return n("green");case"error":default:return n("lightred")}}(e.type,e.title)),r?u.push(m+i,...c,m+i):u.push(...c),0!==c.length&&(u[0]=m+u[0].trimStart(),u.push(m)),n.formatWithOptions({...t},...u)}e.createWithNull=function(e){return l(e)?Object.create(null,e):Object.create(null)},e.deleteAttrs=function(e,t){let n;for(;!u(n=t.pop());)if(!Reflect.deleteProperty(e,n))return t.push(n),d(e,t);return e},e.derive=d,e.isPrototypeProperty=function(e,t){return"object"==typeof(n=e)&&!function(e){return null===e}(n)&&!e.hasOwnProperty(t)&&t in e;var n},e.shallowEqual=function(e,t){if(p(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r=0;r<n.length;r++)if(!g.call(t,n[r])||!p(e[n[r]],t[n[r]]))return!1;return!0},e.stringify=function(e){return new Promise(t=>{try{t(JSON.stringify(e))}catch(t){throw k({name:"stringify",message:"转换字符串失败",data:{value:e,error:t}})}})},e.toLowerCaseKey=function(e,t=!0){const n=new Set;return Reflect.ownKeys(e).reduce((r,o)=>{const i=e[o];return function(e){return"symbol"==typeof e}(o)||s(o)?(r[o]=i,r):(o=o.toLocaleLowerCase(),t?r[o]=i:n.has(o)||(r[o]=i,n.add(o)),r)},{})},Object.defineProperty(e,"__esModule",{value:!0})}));
{
"name": "@curong/object",
"version": "0.0.0-alpha.3",
"version": "0.0.0-alpha.4",
"license": "MIT",

@@ -31,6 +31,7 @@ "author": {

"dependencies": {
"@curong/types": "^0.0.0-alpha.3"
"@curong/term": "^0.0.0-alpha.4",
"@curong/types": "^0.0.0-alpha.4"
},
"sideEffects": false,
"gitHead": "06b69d7d28af0202111c242194269f63a2272a05"
"gitHead": "06ec6b8e05f8f24453e0f0e189494dd69170c3b8"
}

@@ -10,1 +10,3 @@ # `@curong/object`

- `shallowEqual`: 通过浅比较的方式比较两个对象中的属性。(仅比较对象中的一层属性)
- `stringify`: 将一个值转换为一个字符串
- `toLowerCaseKey`: 将一个对象中的键全部转换为小写,并返回一个新的对象
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc