Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
core-functions
Advanced tools
Core functions, utilities and classes for working with Node/JavaScript primitives and built-in objects, including strings, booleans, Promises, base 64, Arrays, Objects, standard AppErrors, etc.
Core functions, utilities and classes for working with Node/JavaScript primitives and built-in objects, including strings, numbers, booleans, Dates, Promises, base 64, Arrays, Objects, standard AppErrors, sorting utilities, etc.
Currently includes:
This module is exported as a Node.js module.
Using npm:
$ {sudo -H} npm i -g npm
$ npm i --save core-functions
In Node.js:
To use the any
utilities
const any = require('core-functions/any');
To use the string utilities
const Strings = require('core-functions/strings');
To use the number utilities
const Numbers = require('core-functions/numbers');
To use the boolean utilities
const Booleans = require('core-functions/booleans');
To use the Base 64 encoding and decoding utilities
const base64 = require('core-functions/base64');
To use the Date utilities
const Dates = require('core-functions/dates');
To use the sorting utilities
const sorting = require('core-functions/sorting');
To use the Promise utilities
const Promises = require('core-functions/promises');
To use the Object utilities
const Objects = require('core-functions/objects');
To use the Array utilities
const Arrays = require('core-functions/arrays');
To use the Timer utilities
const timers = require('core-functions/timers');
To use the Try
, Success
and Failure
classes
const tries = require('./tries');
const Try = tries.Try;
const Success = tries.Success;
const Failure = tries.Failure;
// Simulate getting a Success outcome from successful execution of a function, which returns a value
const outcome = Try.try(() => 'Abc');
// outcome = new Success('Abc')
assert(outcome.isSuccess());
assert(outcome.value === 'Abc');
// using map function to convert a Success('Abc') outcome's value into a Success('AbcXyz')
const outcome1 = outcome.map(v => v + 'Xyz');
assert(outcome1.isSuccess());
assert(outcome1.value === 'AbcXyz');
// Simulate getting a Failure outcome from unsuccessful execution of a function, which throws an error
const testErr = new Error("Err"); // an arbitrary error for the example
const outcome2 = Try.try(() => {throw testErr});
// outcome2 is equivalent to new Failed(new Error("Err"))
assert(outcome2.isFailure());
assert(outcome2.error === testErr);
// using recover function to convert a Failed outcome's error into a Success(123)
const outcome3 = outcome2.recover(err => 123);
assert(outcome3.isSuccess());
assert(outcome3.value === 123);
// ... or using map function to handle both successes & failures cases at the same time (similar to Promise.then)
const outcome4 = outcome.map(
value => {
return value * 42;
},
err => {
console.log(err.stack);
return -1;
}
);
To use the standard application errors
const appErrors = require('core-functions/app-errors');
const AppError = appErrors.AppError;
// 400-series
const BadRequest = appErrors.BadRequest;
const Unauthorized = appErrors.Unauthorized;
const Forbidden = appErrors.Forbidden;
const NotFound = appErrors.NotFound;
const RequestTimeout = appErrors.RequestTimeout;
const TooManyRequests = appErrors.TooManyRequests;
// 500-series
const InternalServerError = appErrors.InternalServerError;
const BadGateway = appErrors.BadGateway;
const ServiceUnavailable = appErrors.ServiceUnavailable;
const GatewayTimeout = appErrors.GatewayTimeout;
// HTTP status codes with explicit class support and allowed to pass through to API Gateway by default
const supportedHttpStatusCodes = appErrors.supportedHttpStatusCodes;
// Error conversion functions
const toAppError = appErrors.toAppError;
const toAppErrorForApiGateway = appErrors.toAppErrorForApiGateway;
This module's unit tests were developed with and must be run with tape. The unit tests have been tested on Node.js v4.3.2.
See the package source for more details.
any
module:
defined
& notDefined
functionsvalueOf
function removed from objects
moduleobjects
:
valueOf
function to any
modulevalueOf
function & delegated it to valueOf
in any
modulesorting
:
isUndefinedOrNull
function & replaced its usage with calls to notDefined
function from any
moduleisUndefinedOrNull
function & delegated it to notDefined
function from any
modulepromises
module:
avoidUnhandledPromiseRejectionWarning
function to avoid unneeded Node 6.10.3 warningspromises
module:
every
& chain
functions to skip marking internal cancelled flags as true on cancellation if already completedflatten
function to avoid the wasted effort of "flattening" non-Success values and/or arrays of non-Success valuesarrays
module:
flatten
functiontries
module:
countSuccess
& describeSuccessAndFailureCounts
methods to count any
non-Failure outcomes as successes (instead of ONLY counting Success outcomes as successes)
strict
argument to these static methods that can be set to true to restore the original
behaviour of ONLY strictly counting Success outcomes as successespromises
module:
installCancel
utility function that installs a cancel
method on a cancellable, which combines any existing
cancel
method behaviour with the given new cancel function logicevery
and chain
functions to use new installCancel
utility function, which enables them to "extend"
the behaviour of their cancellables' cancel methods instead of just overwriting theminstallCancelTimeout
utility function that installs a cancelTimeout
method on a cancellable, which
combines any existing cancelTimeout
method behaviour with the given new cancelTimeout function logicdelay
function to use new installCancelTimeout
utility function, which enables it to "extend" the
behaviour of its cancellable's cancel method instead of just overwriting itchain
function to also pass any and all previous outcomes as an optional 4th argument to the given input
function f
, which enables an input function to use and/or react to previous outcomes in the chainDelayCancelledError
subclass of Errordelay
function to throw a new DelayCancelledError
when timeout triggers and mustResolve is false. Note
that this change is not entirely backward compatible, since it fixes the prior behaviour that was incorrectly
throwing a boolean with the triggered value as the "error"flatten
function to recursively reduce a given Promise or array of Promises (containing other promises
or arrays of promises) down to a single Promise (with any Success and/or Failure outcomes necessary)numbers
, objects
& app-errors
modules:
Number.parseInt(...)
with more reliable & consistent Number(...)
e.g. parseInt('1e+22') returns 1, while Number('1e+22') returns 1e+22;
e.g. parseInt('12B3') returns 12, while Number('12B3') returns NaNobjects
module:
copy
, copyNamedProperties
& merge
functions to the new copying
& merging
modulescopy
, copyNamedProperties
& merge
functions to simply delegate to their counterparts in the new copying
& merging
modules and marked the original functions as deprecatedisTypedArray
, getPropertyNames
, getPropertySymbols
, getPropertyKeys
, getPropertyDescriptors
,
getPropertyValueByKeys
, getPropertyDescriptorByKeys
, getPropertyValueByCompoundName
& getOwnPropertyNamesRecursively
functionsweak-map-copy
module to enable "copying" of WeakMap
instancesweak-set-copy
module to enable "copying" of WeakSet
instancescopying
module:
copy
& copyNamedProperties
functions copied from objects
modulecopy
function to also support copying of property descriptors and copying of
Symbols, Dates, Buffers, ArrayBuffers, TypedArrays, DataViews, Errors, RegExps, Maps, Sets, WeakMaps & WeakSetsdeepMapKeys
, deepMapValues
, deepSets
, onlyEnumerable
, onlyValues
, omitAccessors
, isCopyable
,
createCustomObject
& copyCustomContent
options to enable more extensive customisation of the copy
functionconfigureCopyContext
, isCopyableObject
, copyObject
, createObject
, createTypedArray
,
createDataView
, copyContent
, copyPropertyDescriptors
, copyPropertyValues
, copyPropertyDescriptor
,
copyPropertyValue
& copyDescriptor
supporting functionsmerging
module:
merge
function copied from objects
modulemerge
functionisMergeable
and onlyEnumerable
options to enable more extensive customisation of the merge
functionconfigureMergeContext
, isMergeableObject
, mergeObject
, resolveMergedObject
, mergeContent
,
areSimilarArrayLikes
, mergePropertyDescriptors
& mergePropertyValues
supporting functionstries
module:
simplify
, count
, countSuccess
, countFailure
& describeSuccessAndFailureCounts
static methodsflatten
& findFailure
static methodspromises
module:
CancelledError
constructor unresolvedPromises
parameter to more generic unresolvedInputs
unresolvedInputs
property to CancelledError
class and kept unresolvedPromises
as an alias for itcompleted
property of CancelledError
class, which was incorrectly reporting completed as true when
no unresolved inputs or promises were providedchain
functionstrings
module:
cleanInspectedPromise
functiontype-defs
module:
Outcome
& Outcomes
type definitionscopy.sh
scriptpromises.js
module:
promises
module functions onto native Promise
classtry
function to NOT use Promise.all
when the given function returns an array of promises,
so that it instead preserves ALL of the executed function's returned promises, "wrapped" in a Promise.resolve
allOrOne
and every
functions to both accept any mixture of promise and/or non-promise
values, in order to bring their behaviour in line with that of the standard Promise.all
methodevery
function to ONLY accept an array of promises
(i.e. it no longer supports var args containing
promises) and added a new cancellable
parameter to enable the wait for every promise to complete to be short-
circuited at the earliest possible opportunity and the every
function will then instead return a rejected
CancelledError
from which the resolvedOutcomes
and unresolvedPromises
can be retrievedevery
function's returned resolutions from literal objects containing result
or error
properties
to use the new tries
modules's Success
, Failure
and Try
classes instead (NB: Success has a value
property,
and not a result
property, so this change is not backward-compatible)every
function to return an empty array when the first argument was not a promiseisPromise
function to isPromiseLike
& added new isPromise
function that ONLY returns true for native promisesisArrayOfPromises
function, which was no longer useful & would have had to change after isPromise
changedone
function to convert a single promise into a native Promise that resolves to a Success
or Failure
outcometoPromise
function to attempt to convert a promise-like into a native promise
one
functionevery
function to use it to ensure that the first promise in the chain becomes a native Promisetries.js
module:
Try
superclass and Success
and Failure
subclasses modelled after their same-named Scala counterpartsdates.js
module:
simpleISODateTimeRegex
& simpleISODateRegex
regular expressionsextendedISODateTimeRegex
& extendedISODateRegex
regular expressionsisSimpleISODateTimeLike
& isSimpleISODateLike
functionsisSimpleISODateTime
& isSimpleISODate
functionsisExtendedISODateTimeLike
& isExtendedISODateLike
functionsisExtendedISODateTime
& isExtendedISODate
functionstoSimpleISODateTime
& toSimpleISODate
functionstoDateTime
& toExtendedISODate
functionsisValidDate
functionsorting.js
module:
SortType
"enum" object to defined the types of sorting supportedcompareNumbers
, compareStrings
, compareBooleans
, compareDates
, compareIntegerLikes
&
compareUndefinedOrNull
compare functions to be used with Array sort
methodtoSortable
function, which resolves the appropriate sort type and compare function to use for a given array
of values intended to be sorted and also maps the values into an array of consistent, sortable types of valuessortSortable
function (primarily for testing), which simply sorts a "Sortable" object's sortableValues
using its compare
functionnumbers.js
module:
integerRegex
, numberRegex
, zeroRegex
, leadingZeroesRegex
& trailingZeroesRegex
regular expressionsisInteger
& isSafeInteger
functionsisNumberLike
, isIntegerLike
& isZeroLike
functionstoNumberLike
, toDecimalLike
, toDecimalLikeOrNaN
, toIntegerLike
, toIntegerLikeOrNaN
&
toNumberOrIntegerLike
functionsremoveLeadingZeroes
, removeTrailingZeroes
, zeroPadLeft
& removeSignIfZero
functionsnearlyEqual
function for testing numbers for approximate equalitystrings.js
module:
stringifyKeyValuePairs
functiontoLowerCase
functionstringify
function:
useToStringForErrors
, avoidToJSONMethods
& quoteStrings
parameters with a single, optional opts
parameter with optional avoidErrorToString
(NB: renamed and changed default behaviour to use toString() for
Errors), avoidToJSONMethods
and quoteStrings
properties.opts
object, which means this
API change is still backward-compatibleuseJSONStringify
, replacer
& space
opts properties to enable stringify
's behaviour to be
switched to simply use JSON.stringify
instead via its new opts
argumentobjects.js
module:
toKeyValuePairs
functionmerge
function:
replace
& deep
parameters with a single, optional opts
parameter with optional replace
& deep
propertiesopts
object, which means this
API change is still backward-compatiblecopy
function:
deep
parameter with a single, optional opts
parameter with an optional deep
propertydeep
boolean argument passed instead of a new opts
object, which
means this API change is still backward-compatiblecopyNamedProperties
function:
compact
, deep
& omitPropertyIfUndefined
parameters with a single, optional opts
parameter with
optional replace
, deep
& omitIfUndefined
propertiesopts
object, which means this
API change is still backward-compatibletype-defs
"module" to gather the various type definitions into one placetest/testing.js
copyNamedProperties
function to objects.js
modulegetPropertyValue
function to objects.js
moduleapp-errors.js
module to export getHttpStatus
functionapp-errors.js
module's AppError
constructor:
objects.js
module's copy
and merge
functions:
strings.js
module's stringify
function:
toString
methods, with square brackets (to indicate
that the property does not contain just a string error message)strings.js
module's stringify
function:
toJSON
methods (if any) by default (prior versions did NOT use them at all)avoidToJSONMethods
argument to determine whether to avoid using objects' toJSON methods or not (default)JSON.stringify
name
as the first property, followed by its message
as the second property, followed by the rest of its
enumerable properties (excluding its stack
property)[Reference: {name}]
, whereas the prior version marked them incorrectly as [Circular: {name}]
[Circular: {name}]
strings.js
module's stringify
function:
JSON.stringify
useToStringForErrors
argument to convert Errors using their toString
methods (if true) or
as objects (if false), but with their message
and name
(but not stack
) properties visible in the resultquoteStrings
argument to return given string values surrounded with double-quotes (if true)objects.js
:
merge
functionobjects.js
:
merge
function to handle circular, non-Directed Acyclic Graphs of objectscopy
function also able to handle non-DAGsobjects.js
:
merge
functionstrings.js
:
nthIndexOf
function that finds index of nth occurrence of a search value in a stringpromises.js
:
every
function that accepts multiple promises and returns a single promise that returns a list of either a result or an error for each and every one of the given promisespromises.js
:
isPromise
to survive undefined and nullisArrayOfPromises
function to check if a result is an array of promisesallOrOne
function to transform a result into a single promise
using Promise.all
, the promise-result or Promise.resolve
Promise.try
to use new Promise.allOrOne
allOrOne
& isArrayOfPromises
and more tests for try
x instanceof Array
checks with safer Array.isArray(x)
checkMethodEqual
and checkMethodOkNotOk
functions to show method prefixes properlystringify
function to better handle functions and arraysisPromise
functioncancellable
argument to delay
function to enable cancellation of delay's timeouttrimOrEmpty
functionsafeTrim
function to trim
and changed safeTrim
to an alias for trim
3.0.5
any
module:
defined
& notDefined
functionsvalueOf
function removed from objects
moduleobjects
:
valueOf
function to any
modulevalueOf
function & delegated it to valueOf
in any
modulesorting
:
isUndefinedOrNull
function & replaced its usage with calls to notDefined
function from any
moduleisUndefinedOrNull
function & delegated it to notDefined
function from any
moduleFAQs
Core functions, utilities and classes for working with Node/JavaScript primitives and built-in objects, including strings, booleans, Promises, base 64, Arrays, Objects, standard AppErrors, etc.
The npm package core-functions receives a total of 48 weekly downloads. As such, core-functions popularity was classified as not popular.
We found that core-functions demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.