@hdsydsvenskan/utils
v4.20.3
Published
Misc utility methods that's useful for our sites
Downloads
1,594
Maintainers
Keywords
Readme
Utils
Misc utility methods that's useful for our sites
Installation
npm install --save @hdsydsvenskan/utilsRelease new version
Follow Semantic Versioning and use np and a version like patch | minor | major | prepatch | preminor | premajor | prerelease | 1.2.3
np patchPublic methods
Tiny helpers
resolveValue(value, ...valueArgs)– value can be a function, a Promise or another value. If a function then it will be called withvalueArgs. Returns a PromiseresolveValueRaw(value, ...valueArgs)– same asresolveValue()but without the convenience of always returning the value wrapped in a PromiseresolveValueWithThis(value, thisContext, ...valueArgs)– value can be a function, a Promise or another value. If a function then it will be called withvalueArgsand havethisasthisContext. Returns a PromiseresolveNonObjectValue(value, ...valueArgs)– same asresolveValueRaw(), but with improved and stricter JSDoc typesresolveNonObjectValueRaw(value, ...valueArgs)– same asresolveValueWithThis(), but with improved and stricter JSDoc typesresolveNonObjectValueWithThis(value, thisContext, ...valueArgs)– same asresolveValue(), but with improved and stricter JSDoc typesapplyToDefaults(defaults, data)– appliesdatatodefaults. Mimicks theapplyToDefaultsfrom Hoek.escapedJSONStringify(obj)– returns an escaped stringified JSON object that can safely be printed in HTML.sleep(ms: number, [signal: AbortSignal])– returns aPromisethat resolves aftermsmilliseconds. If thesignalparameter is provided, the promise will resolve the instant the signal is aborted.
Array helpers
arrayIntersect(firstArray, secondArray)– returnstrueorfalsedependening 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 onebisectLeft(sortedArray, value)– find the left-most index of a sorted array where a value can be inserted while maintaining sorted orderbisectRight(sortedArray, value)– Similar tobisectLeft, 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 isundefined, then an empty arrayinsort(sortedArray, value)– creates a new sorted array with the value inserted at the correct index
Object helpers
deepClone(obj)– recursively clonesobjand all objects and arrays it contains.objshould be either an object or an array.deepMerge(target, source)– recursively merges properties fromsourceintotarget. Iftargetis an object (and a property oftargetis an object) then properties will be merged into that object. Else it will be replaced with any new value fromsource.deepFreeze(obj)– recursively freezesobjand all objects and arrays it contains.objcan be either an object or an array.losslessMerge(obj1, obj2)– creates an object with all keys fromobj1andobj2+ 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 outundefineditemsobjectMap(obj, callback(value, key, i))– DEPRECATED BYobjectMapExtended()– like[].map()but returns an objectobjectMapExtended(obj, callback(value, key, i))– like[].map()but returns an objectomit(obj, keys)– returnsobjwith all keys mentioned inkeysomitted.keysbeing an array of stringspick(obj, keys)– likeomit(), but rather than enforcing a blacklist of keys, it enforces a whitelist – only including keys of the object that have been listed inkeyspickDerived(obj, targets)–targetsshould be an object with keys that refer to keys inobjand values that are eithertrue(then the value inobjwill be picked), afunctionthat will be sentobjand will return a derived value, anobjectwhich value will be resolved usingparseDerived(obj, theTargetValue)or a value of another type, which will then be returned as is.recursiveObjectFilter(obj, [callback(value, key, i)])– likeobjectFilter(), but better, since this one is recursive 💪zipObject(keys, values)– returns an object with keys fromkeysand key valies fromvalues
Promise helpers
catchWrap(promise, message)– wraps the error message of a possibly rejected promise with this message throughVErrorobjectPromiseAll(obj, [mapMethod(value, key)])– resolves all Promises inobjand returns a Promise that resolves to an object with all keys ofobjand their respective resolved value. IfmapMethodis set, then it will be called withvalueandkeyof each item inobjand is expected to return a value or Promise to resolve to for each.recursiveObjectPromiseAll(obj)– likeobjectPromiseAll, 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 returnedescapeHTML(value)– currently a re-exportedescape-goat.escapeHTML(), also useable as template tagunescapeHTML(value)– currently a re-exportedescape-goat.unescapeHTML(), also useable as template taginlineString(value)– replaces all newlines, including their surrounding whitespace, with a simple single spacetrimNewlines(value)– replaces all newlines, including their surrounding whitespace, with a simple single newlinewrapIn([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-exportedescape-goat.escapeHTML(), also useable as a simple standalone functionunescapeHTML– currently a re-exportedescape-goat.unescapeHTML(), also useable as a simple standalone functioninlineTemplateTag– same assimpleTemplateTag, 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 stringsimpleTemplateTag– 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.htmlorjstemplateTagWithModifier({ [staticCallback], [valueCallback], [finalCallback] })– makes it simple to create template tags likeinlineTemplateTagandtrimNewlines;trimNewlines– same asinlineTemplateTag, but replaces with a single newline instead
Caching
limitedStore(maxSize)– returns a limited store that saves items up to a limit ofmaxSizeand then removes the oldest item. The returned object has three methods:set(key, value),get(key)andremove(key)memoize(func(args), maxSize, [{ keyGenerator(args), hitrateCallback, maxAge, store }])– memoizes the result of the func using a limited cache of max sizemaxSizewith optionally a max age ofmaxAge, a custom cache key generated bykeyGenerator, ahitrateCallbackthat's called withtruefor every hit andfalsefor every miss and a customstorewith same API aslimitedStore. Returns a wrappedfuncwith an addedresetValue(args)method that can be used to reset the value of a specific cached invocation (useful when eg. a cachedPromisehas been rejected and you want to shorten the wait time).lruMemoize(func(args), maxSize, [{ keyGenerator(args), maxAge, store }])– likememoize()but defaults to a LRU cacheextendedCache(maxSize, [{ hitrateCallback, maxAge, store }])– likememoize(), but without the memoization function. Returns an object with three methods:set(key, value, expires),get(key)andremove(key)whereexpiresshould be a timestamp in milliseconds
Errors and logging
deprecate(name, [message])– logs aconsole.trace()the very first time it's called with a newname, thus avoiding spamming the output with deprecation errors. Tracks state globally. Does not output logs in production.ExtendableError– an extendable helper subclass ofError, which aids in setting things up correctly.findCauseByError(err, FooError)– likeVError.findCauseByName(err, 'FooError')but when it returns an error it actually is an error of theFooErrortypeHdsUtilsFetchError(res, parsed)– fetch relatedErrorclass, can be used wherever a fetch related error happenslogSlowPromise(inputPromise, name, { logger, [logLevel], [warnEveryMs], [thresholdInMs]})– logs (by default atwarnlevel) whenever the wrappedPromiseis 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 localdeprecate()that only tracksname:s within itself and not globally.logdefaults toconsole.trace()
GraphQL helpers
formatFieldsAndFragments({ fields, fragments }, spacing = ' ')– used in GraphQL fragment extensions to formatfieldsandfragments(both being arrays of strings and optional) for direct inclusion into a GraphQL query string. Thespacingcan 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 }wheredependenciesare what is to be added to a GraphQL query's dependencies andfieldsare 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 between0and 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" – returnstrueeg. if its falsy, equal to'null'or'undefined'or if it just contains whitespace. Else it returnsfalseisFalsyishString(value)– likeisEmptyishString()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 errorreadFilesInDir(path)– returns a promise that resolves to an object with file names as keys and content as valuesrenderTpl(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.
