DEV Community

Cover image for The toolkit-use npm package has added some shared utility methods
toolkituse
toolkituse

Posted on

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

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
}
Enter fullscreen mode Exit fullscreen mode

Check if a value is defined and not null

export const isDef = (v: any) => {
  return v !== undefined && v !== null
}
Enter fullscreen mode Exit fullscreen mode

Check if a value is true

export const isTrue = (v: any) => {
  return v === true
}

export const isFalse = (v: any) => {
  return v === false
}
Enter fullscreen mode Exit fullscreen mode

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'
  )
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Check if a value is a Promise function

export const isPromise = (val: any) => {
  return (
    isDef(val) &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Convert a value to a number

export const toNumber = (val: any) => {
  const n = parseFloat(val);
  return isNaN(n) ? val : n
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Assign properties of one object to another

export function extend (to, _from) {
  for (var key in _from) {
    to[key] = _from[key];
  }
  return to
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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))
  })
}
Enter fullscreen mode Exit fullscreen mode

Convert camelCase to kebab-case

export const capitalize = cached(function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
});
Enter fullscreen mode Exit fullscreen mode

Convert camelCase to kebab-case

export const hyphenate = cached(function (str) {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
});
Enter fullscreen mode Exit fullscreen mode

Convert kebab-case to camelCase

export const camelize = cached(function (str) {
  return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
Enter fullscreen mode Exit fullscreen mode

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]; }
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Execute a function only once

export function once (fn) {
  var called = false;
  return function () {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Define properties on an object

export const def = (obj, key, value) => {
  Object.defineProperty(obj, key, {
      configurable: true,  // Configurable
      enumerable: false,  // Not enumerable
      value
  });
};
Enter fullscreen mode Exit fullscreen mode

Get the toString method from the object's prototype

export const objectToString = Object.prototype.toString;
Enter fullscreen mode Exit fullscreen mode

Function to get the type string of a value

export const toTypeString = (value) => objectToString.call(value);
Enter fullscreen mode Exit fullscreen mode

Check if a value is an array

export const isArray = Array.isArray;
Enter fullscreen mode Exit fullscreen mode

Check if a value is a map

export const isMap = (val) => toTypeString(val) === '[object Map]';
Enter fullscreen mode Exit fullscreen mode

Check if a value is a set

export const isSet = (val) => toTypeString(val) === '[object Set]';
Enter fullscreen mode Exit fullscreen mode

Check if a value is a date

export const isDate = (val) => val instanceof Date;
Enter fullscreen mode Exit fullscreen mode

Check if a value is a function

export const isFunction = (val) => typeof val === 'function';
Enter fullscreen mode Exit fullscreen mode

Check if a value is a string

export const isString = (val) => typeof val === 'string';
Enter fullscreen mode Exit fullscreen mode

Check if a value is a symbol

export const isSymbol = (val) => typeof val === 'symbol';
Enter fullscreen mode Exit fullscreen mode

Check if a key is an integer key

export const isIntegerKey = (key) => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key;
Enter fullscreen mode Exit fullscreen mode

Invoke an array of functions with an argument

export const invokeArrayFns = (fns, arg) => {
  for (let i = 0; i < fns.length; i++) {
      fns[i](arg);
  }
};
Enter fullscreen mode Exit fullscreen mode

Compare two values for equality using Object.is

export const hasChanged = (value, oldValue) => !Object.is(value, oldValue)
}
Enter fullscreen mode Exit fullscreen mode

Please note that the translation provided may require further adjustment based on the specific context and usage of these utility methods.

Top comments (4)

Collapse
 
soumyadeepdey profile image
Soumyadeep Dey ☑️

Informative

Collapse
 
toolkituse profile image
toolkituse

yes,This is the npm package I wrote, you can try to use it, or contribute together

github.com/KenNaNa/toolkit-use

Collapse
 
toolkituse profile image
toolkituse

yes,This is the npm package I wrote, you can try to use it, or contribute together

github.com/KenNaNa/toolkit-use

Collapse
 
adambright profile image
Adam Bright • Edited

Please tell me it's a joke... This is why I hate javascript. Is there really a need for isTrue function? Why isUndef also checks for null? Why should there be an alias like hasOwn ? 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?