The toolkit-use npm package has added some shared utility methods
Tags: npm, opensource, typescript, programming
Published: 2023-07-12 01:40:00

The toolkit-use npm package has added some shared utility methods

[The toolkit-use npm package has added some shared utility methods](https://github.com/KenNaNa/toolkit-use/blob/main/src/shared/index.ts)

Here is the translation of the provided code:

import { hyphenateRE, camelizeRE } from '../regex/index'

## Check if a value is undefined or null
```ts
export const isUndef = (v: any) => {
  return v === undefined || v === null
}
```

## Check if a value is defined and not null
```ts
export const isDef = (v: any) => {
  return v !== undefined && v !== null
}
```

## Check if a value is true
```ts
export const isTrue = (v: any) => {
  return v === true
}

export const isFalse = (v: any) => {
  return v === false
}
```


## Check if a value is a primitive type
```ts
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
```ts
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
```ts
export const isPromise = (val: any) => {
  return (
    isDef(val) &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}
```
## Get the raw type string of a value
```ts
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
```ts
const hasOwnProperty = Object.prototype.hasOwnProperty
export const  hasOwn = (obj: any, key: any) => {
  return hasOwnProperty.call(obj, key)
}
```

## Convert a value to a number
```ts
export const toNumber = (val: any) => {
  const n = parseFloat(val);
  return isNaN(n) ? val : n
}
```

## The object to inspect
```ts
/**
 * @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
```ts
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
```ts
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
```ts
export function extend (to, _from) {
  for (var key in _from) {
    to[key] = _from[key];
  }
  return to
}
```

## Merge an array of objects into one object
```ts
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
```ts
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
```ts
export const capitalize = cached(function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
});
```

## Convert camelCase to kebab-case
```ts
export const hyphenate = cached(function (str) {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
});
```

## Convert kebab-case to camelCase
```ts
export const camelize = cached(function (str) {
  return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
```

## Create a map
```ts
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
```ts
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
```ts
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
```ts
export function once (fn) {
  var called = false;
  return function () {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  }
}
```

## Compare two arrays for equality
```ts
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
```ts
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
```ts
export const objectToString = Object.prototype.toString;
```

## Function to get the type string of a value
```ts
export const toTypeString = (value) => objectToString.call(value);
```

## Check if a value is an array
```ts
export const isArray = Array.isArray;
```

## Check if a value is a map
```ts
export const isMap = (val) => toTypeString(val) === '[object Map]';
```

## Check if a value is a set
```ts
export const isSet = (val) => toTypeString(val) === '[object Set]';
```

## Check if a value is a date
```ts
export const isDate = (val) => val instanceof Date;
```

## Check if a value is a function
```ts
export const isFunction = (val) => typeof val === 'function';
```

## Check if a value is a string
```ts
export const isString = (val) => typeof val === 'string';
```

## Check if a value is a symbol
```ts
export const isSymbol = (val) => typeof val === 'symbol';
```

## Check if a key is an integer key
```ts
export const isIntegerKey = (key) => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key;
```

## Invoke an array of functions with an argument
```ts
export const invokeArrayFns = (fns, arg) => {
  for (let i = 0; i < fns.length; i++) {
      fns[i](arg);
  }
};
```

## Compare two values for equality using `Object.is`
```ts
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.