The toolkit-use npm package has added some shared utility methods
The toolkit-use npm package has added some shared utility methods
Here is the translation of the provided code:
import { hyphenateRE, camelizeRE } from '../regex/index'
Check if a value is undefined or null
export const isUndef = (v: any) => {
return v === undefined || v === null
}
Check if a value is defined and not null
export const isDef = (v: any) => {
return v !== undefined && v !== null
}
Check if a value is true
export const isTrue = (v: any) => {
return v === true
}
export const isFalse = (v: any) => {
return v === false
}
Check if a value is a primitive type
export const isPrimitive = (v: any) => {
return (
typeof v === 'string' ||
typeof v === 'number' ||
typeof v === 'symbol' ||
typeof v === 'boolean'
)
}
Check if a value is an object (reference type) or created using the 'new' keyword
export const isObject = (obj: any) => {
return obj !== null && typeof obj === 'object' // Note the 'null' in the typeof check
}
Check if a value is a Promise function
export const isPromise = (val: any) => {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}
Get the raw type string of a value
const _toString = Object.prototype.toString
export const toRawType = (val: any) => {
return _toString.call(val).slice(8, -1)
}
Check if an object has a specific property
const hasOwnProperty = Object.prototype.hasOwnProperty
export const hasOwn = (obj: any, key: any) => {
return hasOwnProperty.call(obj, key)
}
Convert a value to a number
export const toNumber = (val: any) => {
const n = parseFloat(val);
return isNaN(n) ? val : n
}
The object to inspect
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
export function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false
let proto = Object.getPrototypeOf(obj)
// 1. edge case Object.create(null)
if (proto === null) return true
let baseProto = proto
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto)
}
// 2. Compare the first and last prototypes in the prototype chain
return proto === baseProto
}
Convert a value to a string
export const toString = (val: any) => {
return val == null
? ''
: Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
? JSON.stringify(val, null, 2) // For arrays or objects
: String(val)
}
Convert an array-like object to an array
export function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
Assign properties of one object to another
export function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
Merge an array of objects into one object
export function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
If the argument is a function, return a cached version of it
export function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str]; // Cache lookup
return hit || (cache[str] = fn(str))
})
}
Convert camelCase to kebab-case
export const capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
Convert camelCase to kebab-case
export const hyphenate = cached(function (str) {
return str.replace(hyphenateRE, '-$1').toLowerCase()
});
Convert kebab-case to camelCase
export const camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
Create a map
export function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
Check if two objects are equal
export function looseEqual (a, b) {
// Return true if a and b are strictly equal
if (a === b) { return true }
var isObjectA = isObject(a);
var isObjectB = isObject(b);
// Check if both are objects (reference types)
if (isObjectA && isObjectB) {
try {
var isArrayA = Array.isArray(a);
var isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
// If both are arrays, compare their lengths and recursively check each item, return false if they differ
return a.length === b.length && a.every(function (e, i) {
return looseEqual(e, b[i])
})
} else if (a instanceof Date && b instanceof Date) {
// If both are Date objects, compare them using their timestamps
return a.getTime() === b.getTime()
} else if (!isArrayA && !isArrayB) {
// If both are objects, compare their property values recursively if their lengths match, return false if they differ
var keysA = Object.keys(a);
var keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(function (key) {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false
}
} catch (e) {
/* istanbul ignore next */
return false
}
} else if (!isObjectA && !isObjectB) {
// If both are not objects (primitive types), convert them to strings and compare
return String(a) === String(b)
} else {
return false
}
}
Remove an item from an array
export function remove (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
Execute a function only once
export function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
Compare two arrays for equality
export function looseCompareArrays(a, b) {
// If the lengths differ, return false
if (a.length !== b.length)
return false;
let equal = true;
// If the lengths are the same, compare each item in the arrays
for (let i = 0; equal && i < a.length; i++) {
equal = looseEqual(a[i], b[i]);
}
return equal;
}
Define properties on an object
export const def = (obj, key, value) => {
Object.defineProperty(obj, key, {
configurable: true, // Configurable
enumerable: false, // Not enumerable
value
});
};
Get the toString
method from the object's prototype
export const objectToString = Object.prototype.toString;
Function to get the type string of a value
export const toTypeString = (value) => objectToString.call(value);
Check if a value is an array
export const isArray = Array.isArray;
Check if a value is a map
export const isMap = (val) => toTypeString(val) === '[object Map]';
Check if a value is a set
export const isSet = (val) => toTypeString(val) === '[object Set]';
Check if a value is a date
export const isDate = (val) => val instanceof Date;
Check if a value is a function
export const isFunction = (val) => typeof val === 'function';
Check if a value is a string
export const isString = (val) => typeof val === 'string';
Check if a value is a symbol
export const isSymbol = (val) => typeof val === 'symbol';
Check if a key is an integer key
export const isIntegerKey = (key) => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key;
Invoke an array of functions with an argument
export const invokeArrayFns = (fns, arg) => {
for (let i = 0; i < fns.length; i++) {
fns[i](arg);
}
};
Compare two values for equality using Object.is
export const hasChanged = (value, oldValue) => !Object.is(value, oldValue)
}
Please note that the translation provided may require further adjustment based on the specific context and usage of these utility methods.
Top comments (4)
Informative
yes,This is the npm package I wrote, you can try to use it, or contribute together
github.com/KenNaNa/toolkit-use
yes,This is the npm package I wrote, you can try to use it, or contribute together
github.com/KenNaNa/toolkit-use
Please tell me it's a joke... This is why I hate javascript. Is there really a need for
isTrue
function? WhyisUndef
also checks fornull
? Why should there be an alias likehasOwn
?hasChanged
is basically a function of function call with negation.toNumber
returns only floats and suppresses errors...Most of actually useful stuff is already covered by libraries like lodash with better documentation and TESTS.
And this post is basically copy-paste of a source code with some styling over it. Why?