@hdsydsvenskan/utils
TypeScript icon, indicating that this package has built-in type declarations

4.20.3 • Public • Published

Utils

Misc utility methods that's useful for our sites

Installation

npm install --save @hdsydsvenskan/utils

Release new version

Follow Semantic Versioning and use np and a version like patch | minor | major | prepatch | preminor | premajor | prerelease | 1.2.3

np patch

Public methods

Tiny helpers

  • resolveValue(value, ...valueArgs) – value can be a function, a Promise or another value. If a function then it will be called with valueArgs. Returns a Promise
  • resolveValueRaw(value, ...valueArgs) – same as resolveValue() but without the convenience of always returning the value wrapped in a Promise
  • resolveValueWithThis(value, thisContext, ...valueArgs) – value can be a function, a Promise or another value. If a function then it will be called with valueArgs and have this as thisContext. Returns a Promise
  • resolveNonObjectValue(value, ...valueArgs) – same as resolveValueRaw(), but with improved and stricter JSDoc types
  • resolveNonObjectValueRaw(value, ...valueArgs) – same as resolveValueWithThis(), but with improved and stricter JSDoc types
  • resolveNonObjectValueWithThis(value, thisContext, ...valueArgs) – same as resolveValue(), but with improved and stricter JSDoc types
  • applyToDefaults(defaults, data) – applies data to defaults. Mimicks the applyToDefaults from Hoek.
  • escapedJSONStringify(obj) – returns an escaped stringified JSON object that can safely be printed in HTML.
  • sleep(ms: number, [signal: AbortSignal]) – returns a Promise that resolves after ms milliseconds. If the signal parameter is provided, the promise will resolve the instant the signal is aborted.

Array helpers

  • arrayIntersect(firstArray, secondArray) – returns true or false dependening whether the two arrays intersect or not.
  • arrayIntersection(firstArray, secondArray) – returns the values that are present in both arrays.
  • arrayNonIntersection(firstArray, secondArray) – returns the values in the first array that are not present in the second array.
  • arrayZip(firstArray, secondArray) – zips two arrays of the same length into one
  • bisectLeft(sortedArray, value) – find the left-most index of a sorted array where a value can be inserted while maintaining sorted order
  • bisectRight(sortedArray, value) – Similar to bisectLeft, but finds the right-most index instead.
  • ensureArray(maybeArray) – always returns an array, either the array input, the input wrapped as an array, or if the input is undefined, then an empty array
  • insort(sortedArray, value) – creates a new sorted array with the value inserted at the correct index

Object helpers

  • deepClone(obj) – recursively clones obj and all objects and arrays it contains. obj should be either an object or an array.
  • deepMerge(target, source) – recursively merges properties from source into target. If target is an object (and a property of target is an object) then properties will be merged into that object. Else it will be replaced with any new value from source.
  • deepFreeze(obj) – recursively freezes obj and all objects and arrays it contains. obj can be either an object or an array.
  • losslessMerge(obj1, obj2) – creates an object with all keys from obj1 and obj2 + with all values from the two merged into arrays. If a value in either was an array, then the content of that array gets merged into the array rather than the array itself.
  • objectFilter(obj, [callback(value, key, i)]) – like [].filter() but returns an object. Defaults to filter out undefined items
  • objectMap(obj, callback(value, key, i))DEPRECATED BY objectMapExtended() – like [].map() but returns an object
  • objectMapExtended(obj, callback(value, key, i)) – like [].map() but returns an object
  • omit(obj, keys) – returns obj with all keys mentioned in keys omitted. keysbeing an array of strings
  • pick(obj, keys) – like omit(), but rather than enforcing a blacklist of keys, it enforces a whitelist – only including keys of the object that have been listed in keys
  • pickDerived(obj, targets)targets should be an object with keys that refer to keys in obj and values that are either true (then the value in obj will be picked), a function that will be sent obj and will return a derived value, an object which value will be resolved using parseDerived(obj, theTargetValue) or a value of another type, which will then be returned as is.
  • recursiveObjectFilter(obj, [callback(value, key, i)]) – like objectFilter(), but better, since this one is recursive 💪
  • zipObject(keys, values) – returns an object with keys from keys and key valies from values

Promise helpers

  • catchWrap(promise, message) – wraps the error message of a possibly rejected promise with this message through VError
  • objectPromiseAll(obj, [mapMethod(value, key)]) – resolves all Promises in obj and returns a Promise that resolves to an object with all keys of obj and their respective resolved value. If mapMethod is set, then it will be called with value and key of each item in obj and is expected to return a value or Promise to resolve to for each.
  • recursiveObjectPromiseAll(obj) – like objectPromiseAll, but recursive

String helpers

  • commaSeparatedStringToArray(value) – value should be a string with values separated by a comma and an array of non-falsy values will be returned
  • escapeHTML(value) – currently a re-exported escape-goat.escapeHTML(), also useable as template tag
  • unescapeHTML(value) – currently a re-exported escape-goat.unescapeHTML(), also useable as template tag
  • inlineString(value) – replaces all newlines, including their surrounding whitespace, with a simple single space
  • trimNewlines(value) – replaces all newlines, including their surrounding whitespace, with a simple single newline
  • wrapIn([prefix], value, [suffix]) – adds a prefix and/or suffix to a string if that string is non-empty, else just returns an empty-string

Template tags

  • escapeHTML – currently a re-exported escape-goat.escapeHTML(), also useable as a simple standalone function
  • unescapeHTML – currently a re-exported escape-goat.unescapeHTML(), also useable as a simple standalone function
  • inlineTemplateTag – same as simpleTemplateTag, but replaces all newlines, including their surrounding whitespace, with a simple single space + also trims any space in the very beginning and end of the string
  • simpleTemplateTag – noop template literal tag, works as if no template tag has been added. Makes it easy to get syntax highlighting, by aliasing it as eg. html or js
  • templateTagWithModifier({ [staticCallback], [valueCallback], [finalCallback] }) – makes it simple to create template tags like inlineTemplateTag and trimNewlines;
  • trimNewlines – same as inlineTemplateTag, but replaces with a single newline instead

Caching

  • limitedStore(maxSize) – returns a limited store that saves items up to a limit of maxSize and then removes the oldest item. The returned object has three methods: set(key, value), get(key) and remove(key)
  • memoize(func(args), maxSize, [{ keyGenerator(args), hitrateCallback, maxAge, store }]) – memoizes the result of the func using a limited cache of max size maxSize with optionally a max age of maxAge, a custom cache key generated by keyGenerator, a hitrateCallback that's called with true for every hit and false for every miss and a custom store with same API as limitedStore. Returns a wrapped func with an added resetValue(args) method that can be used to reset the value of a specific cached invocation (useful when eg. a cached Promise has been rejected and you want to shorten the wait time).
  • lruMemoize(func(args), maxSize, [{ keyGenerator(args), maxAge, store }]) – like memoize() but defaults to a LRU cache
  • extendedCache(maxSize, [{ hitrateCallback, maxAge, store }]) – like memoize(), but without the memoization function. Returns an object with three methods: set(key, value, expires), get(key) and remove(key) where expires should be a timestamp in milliseconds

Errors and logging

  • deprecate(name, [message]) – logs a console.trace() the very first time it's called with a new name, thus avoiding spamming the output with deprecation errors. Tracks state globally. Does not output logs in production.
  • ExtendableError – an extendable helper subclass of Error, which aids in setting things up correctly.
  • findCauseByError(err, FooError) – like VError.findCauseByName(err, 'FooError') but when it returns an error it actually is an error of the FooError type
  • HdsUtilsFetchError(res, parsed) – fetch related Error class, can be used wherever a fetch related error happens
  • logSlowPromise(inputPromise, name, { logger, [logLevel], [warnEveryMs], [thresholdInMs]}) – logs (by default at warn level) whenever the wrapped Promise is slower than the set threshold (by default same as the interval) and repeats it on the set interval (by default 500 ms).
  • trackDeprecation([scope], [log]) – creates a local deprecate() that only tracks name:s within itself and not globally. log defaults to console.trace()

GraphQL helpers

  • formatFieldsAndFragments({ fields, fragments }, spacing = ' ') – used in GraphQL fragment extensions to format fields and fragments (both being arrays of strings and optional) for direct inclusion into a GraphQL query string. The spacing can be overridden to better suit the insert position in the GraphQL query.
  • getFieldsAndDependencies({ dependencies, fields, fragments }) – used in extendable GraphQL queries to format and merge the input data (all being arrays of strings and optional) into { dependencies, fields } where dependencies are what is to be added to a GraphQL query's dependencies and fields are what to be inserted into the GraphQL query string.

Randomness helpers

  • seededRandom(seed) – returns a function that generates a random number. The returned function requires an integer as its only argument, the random number returned will be an integer between 0 and the sent in integer (not including the sent in integer).
  • createMemoizedSeededListSorter – makes it possible to sort a list consistently across many places both within and across instances, based on the sent in seed. Check the code in this project as well as the uses in other projects to understand how it works. It's a bit complicated

Validators

  • isEmptyishString(value, [{ treatNonStringsAsNonEmpty = false }]) – checks if the value is a string and if it is "emptyish" – returns true eg. if its falsy, equal to 'null' or 'undefined' or if it just contains whitespace. Else it returns false
  • isFalsyishString(value) – like isEmptyishString() but also checks if the value is equal to 'false' or '0'
  • isValidUUID(stringValue) – checks whether the string value is setup according to a very basic regexp structure

Misc helpers

  • processFetchResponse(fetchPromise) – returns parsed JSON on a 2xx success code, else returns an informative error
  • readFilesInDir(path) – returns a promise that resolves to an object with file names as keys and content as values
  • renderTpl(template, vars, [{ [customFilters] }]) – replaces named placeholders, {{name}}, with variable values and applying optional filters, {{name | filter-name}}. Supported filters are: escape, inline, json. Inspired by Liquid.

Readme

Keywords

none

Package Sidebar

Install

npm i @hdsydsvenskan/utils

Weekly Downloads

790

Version

4.20.3

License

UNLICENSED

Unpacked Size

122 kB

Total Files

72

Last publish

Collaborators

  • jackesa
  • bnsuswol
  • adamosterlund
  • takolander
  • andreas.samuelsson
  • bonniererikrosberg
  • vitryssen
  • johngustav
  • rickardk_
  • herbola
  • ninhow
  • morre
  • maria.rudolphi
  • coulrophobiac
  • tobiasharle
  • j0n
  • emilbjorklund
  • nifo
  • mikael.mattsson
  • jonaek
  • linusthiel-bn
  • johangrahn
  • jon.eldeklint