JSPM

  • Created
  • Published
  • Downloads 1390
  • Score
    100M100P100Q106346F
  • License ISC

AK's collections of useful things...

Package Exports

  • ak-tools
  • ak-tools/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ak-tools) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

ak-tools

AK's collections of useful things...cobbled together from various projects over the years...

install:

$ npm i ak-tools

use:

const utils = require('ak-tools') 		//cjs
import {* as utils} from 'ak-tools' 	//esm

if using an IDE with jsdoc support you should have a good experience.

API

Objects

files : object

file managment

validation : object

data validation utilities

display : object

display, formatting, and other "make it look right" utilities

calculations : object

functions for maths, crypto, and calculations

objects : object

object utilities

arrays : object

array utilities

functions : object

function utilities

logging : object

logging, timers and other diagnostic utilities

Functions

ls([dir], [objectMode])Promise.<any>

list directory contents

rm(fileNameOrPath)Promise.<(string|boolean|void)>

remove a file or directory

touch(fileNameOrPath, [data], [isJson])Promise.<(string|false)>

create a file

load(fileNameOrPath, [isJson], [encoding])

load a filed into memory

mkdir([dirPath])

make a directory

isJSONStr(string)boolean

test if string has JSON structure; if true it can be safely parsed

isJSON(data)boolean

test if data can be stringified as JSON

is(type, val)boolean

check if a type matches a value

isNil(val)boolean

check if a val is null or undefined

comma(num)string

turn a number into a comma separated value; 1000 => "1,000"

truncate(text, chars, [useWordBoundary])string

truncate a string; using an elipses (...)

bytesHuman(bytes, [si], [dp])string

turn a number (of bytes) into a human readable string

json(data, [padding])string

stringify object to json

stripHTML(str)string

strip all <html> tags from a string

multiReplace(str, [replacePairs])string

find and replace many values in string

replaceAll(oldVal, newVal)string

replace all occurance of old with new

toCSV(arr, [headers], [delimiter])string

convert array of arrays to CSV like string

dupeVals(array, [times])Array.<any>

duplicate values within an array N times

rand(min, max)number

random integer between min and max (inclusive)

avg(...nums)number

calculate average of ...nums

calcSize(data)number

calculate the size (on disk)

round(number, [decimalPlaces])number

round a number to a number of decimal places

uid([length])string

generate a random uid:

  • 6NswVtnKWsvRGNTi0H2YtuqGwsqJi4dKW6qUgSiUx1XNctr4rkGRFOA9HRl9i60S
uuid()string

generated a uuid in v4 format:

  • 72452488-ded9-46c1-8c22-2403ea924a8e
rnKeys(obj, newKeys)Object

rename object keys with a mapping object {oldKey: newKey}

rnVals(obj, pairs)Object

rename object values using a mapping array

objFilter(hash, test_function)Object

filter arrays by values or objects by keys

objClean(obj)

removes the following from deeply nested objects:

  • null
  • undefined
  • {}
  • []
objDefault(obj, defs)Object

apply default props to an object; don't override values from source

objMatch(obj, source)boolean

deep equality match for any two objects

clone(thing, [opts])Object

an efficient way to clone an Object; outpreforms JSON.parse(JSON.strigify()) by 100x

typecastInt(obj, [isClone])Object

visit every property of an object a turn "number" values into numbers

  • ex: {foo: {bar: '42'}} => {foo: {bar: 42}}
awaitObj(obj)Promise

utility to await object values

  • ex: {foo: await bar()}
removeNulls(objWithNullOrUndef)Object

explicitly remove keys with null or undefined values; mutates object

  • ex: {foo: "bar", baz: null} => {foo: "bar"}
makeInteger(value)number | NaN

check if a value is an integer, if so return it

dedupe(arrayOfThings)Array.<any>

de-dupe array of objects w/Set, stringify, parse

dedupeVal(arr, keyNames)Array.<any>

de-dupe array of objects by value of specific keys

chunk(sourceArray, chunkSize)Array.<any>

chunk array of objects into array of arrays with each less than or equal to chunkSize

  • [{},{},{},{}] => [[{},{}],[{},{}]]
shuffle(array, [mutate])Array.<any>

fisher-yates shuffle of array elements

range(min, max, [step])Array.<number>

the classic python built-in for generating arrays of integers

deepFlat(arr)Array.<any>

recursively and deeply flatten a nested array of objects

  • ex: [ [ [{},{}], {}], {} ] => [{},{},{},{}]
strToArr(str)Array.<string>

extract words from a string as an array

  • ex "foo bar baz" => ['foo','bar','baz']
attempt(fn, ...args)

try{} catch{} a function; return results

times(n, iteratee)

do a function N times

throttle(func, wait, [options])

throttle a functions's execution every N ms

compose()function

compose functions, left-to-right

  • ex: c(a,b,c) => a(b(c()))
id(any)any

a function which returns it's value

cLog(data, message, [severity])

a cloud function compatible console.log()

log(item, [depth], [maxDepth])void

a comprehensive logging utility in all terminal environments

progress(thing, p, message)void

dumb progress bar; incrementing console message

  • ex: thing message #
time(label)Timer

returns a timer with the following API

  • timer.start()
  • timer.end()
  • timer.report()
  • timer.prettyTime()
quickTime(callback)

a very quick way to check the length of a function; uses console.time

  • ex: timeTaken(main)
tracker([app], [token], [distinct_id])function

track stuff to mixpanel

  • ex: var t = track(); t('foo', {bar: "baz"})
sleep(ms)

arbitrary sleep for N ms

files : object

file managment

Kind: global namespace

validation : object

data validation utilities

Kind: global namespace

display : object

display, formatting, and other "make it look right" utilities

Kind: global namespace

calculations : object

functions for maths, crypto, and calculations

Kind: global namespace

objects : object

object utilities

Kind: global namespace

arrays : object

array utilities

Kind: global namespace

functions : object

function utilities

Kind: global namespace

logging : object

logging, timers and other diagnostic utilities

Kind: global namespace

ls([dir], [objectMode]) ⇒ Promise.<any>

list directory contents

Kind: global function
Returns: Promise.<any> - [] of files in folder

Param Type Default Description
[dir] string "&quot;./&quot;" directory to enumerate; default ./
[objectMode] boolean false return {name: path} instead of [path]; default false

rm(fileNameOrPath) ⇒ Promise.<(string|boolean|void)>

remove a file or directory

Kind: global function
Returns: Promise.<(string|boolean|void)> - path or false if fail

Param Type Description
fileNameOrPath string file or path to be removed

touch(fileNameOrPath, [data], [isJson]) ⇒ Promise.<(string|false)>

create a file

Kind: global function
Returns: Promise.<(string|false)> - the name of the file

Param Type Default Description
fileNameOrPath string file to create
[data] string "&quot;&quot;" data to write; default ""
[isJson] boolean false is data JSON; default false

load(fileNameOrPath, [isJson], [encoding])

load a filed into memory

Kind: global function

Param Type Default Description
fileNameOrPath string file to create
[isJson] boolean false is data JSON; default false
[encoding] string "utf-8" file encoring; default utf-8

mkdir([dirPath])

make a directory

Kind: global function

Param Type Default Description
[dirPath] string "&quot;./tmp&quot;" path to create; default ./tmp

isJSONStr(string) ⇒ boolean

test if string has JSON structure; if true it can be safely parsed

Kind: global function

Param Type
string string

isJSON(data) ⇒ boolean

test if data can be stringified as JSON

Kind: global function

Param Type
data string | JSON

is(type, val) ⇒ boolean

check if a type matches a value

Kind: global function

Param Type Description
type any a native type like Number or Boolean
val any any value to check

isNil(val) ⇒ boolean

check if a val is null or undefined

Kind: global function

Param Type Description
val any value to check

comma(num) ⇒ string

turn a number into a comma separated value; 1000 => "1,000"

Kind: global function
Returns: string - formatted number

Param Type
num string | number

truncate(text, chars, [useWordBoundary]) ⇒ string

truncate a string; using an elipses (...)

Kind: global function
Returns: string - truncated string

Param Type Default Description
text string text to truncate
chars number 500 # of max characters
[useWordBoundary] boolean true don't break words; default true

bytesHuman(bytes, [si], [dp]) ⇒ string

turn a number (of bytes) into a human readable string

Kind: global function
Returns: string - # of bytes

Param Type Default Description
bytes number number of bytes to convert
[si] boolean false threshold of 1000 or 1024; default false
[dp] number 2 decmimal points; default 2

json(data, [padding]) ⇒ string

stringify object to json

Kind: global function
Returns: string - valid json

Param Type Default Description
data object any serializable object
[padding] number 2 padding to use

stripHTML(str) ⇒ string

strip all <html> tags from a string

Kind: global function
Returns: string - sanitized string
Note: note: <br> tags are replace with \n

Param Type Description
str string string with html tags

multiReplace(str, [replacePairs]) ⇒ string

find and replace many values in string

Kind: global function
Returns: string - multi-replaced string

Param Type Default Description
str string string to replace
[replacePairs] Array.<Array> [[" "],["<"],[">"]]

replaceAll(oldVal, newVal) ⇒ string

replace all occurance of old with new

Kind: global function
Returns: string - replaced result
Note: this can't be called on any string directly

Param Type Description
oldVal string | RegExp old value
newVal string new value

toCSV(arr, [headers], [delimiter]) ⇒ string

convert array of arrays to CSV like string

Kind: global function
Returns: string - a valid CSV

Param Type Default Description
arr Array.<Array> data of the form [ [], [], [] ]
[headers] Array.<String> [] header column
[delimiter] string "," delimeter for cells; default ,

dupeVals(array, [times]) ⇒ Array.<any>

duplicate values within an array N times

Kind: global function
Returns: Array.<any> - duplicated array

Param Type Default Description
array Array.<any> array to duplicate
[times] number 1 number of dupes per item

rand(min, max) ⇒ number

random integer between min and max (inclusive)

Kind: global function
Returns: number - random number

Param Type Default Description
min number 1 minimum
max number 100 maximum

avg(...nums) ⇒ number

calculate average of ...nums

Kind: global function
Returns: number - average

Param Type Description
...nums number numbers to average

calcSize(data) ⇒ number

calculate the size (on disk)

Kind: global function
Returns: number - estimated size in bytes

Param Type Description
data JSON JSON to estimate

round(number, [decimalPlaces]) ⇒ number

round a number to a number of decimal places

Kind: global function
Returns: number - rounded number

Param Type Default Description
number number number to round
[decimalPlaces] number 0 decimal places; default 0

uid([length]) ⇒ string

generate a random uid:

  • 6NswVtnKWsvRGNTi0H2YtuqGwsqJi4dKW6qUgSiUx1XNctr4rkGRFOA9HRl9i60S

Kind: global function
Returns: string - a uid of specified length

Param Type Default Description
[length] number 64 length of id

uuid() ⇒ string

generated a uuid in v4 format:

  • 72452488-ded9-46c1-8c22-2403ea924a8e

Kind: global function
Returns: string - a uuid

rnKeys(obj, newKeys) ⇒ Object

rename object keys with a mapping object {oldKey: newKey}

Kind: global function
Returns: Object - new object with renamed keys

Param Type Description
obj Object object to rename
newKeys Object map of form {oldKey: newKey}

rnVals(obj, pairs) ⇒ Object

rename object values using a mapping array

Kind: global function
Returns: Object - object with renamed values

Param Type Description
obj Object
pairs Array.<Array> [['old', 'new']]

objFilter(hash, test_function) ⇒ Object

filter arrays by values or objects by keys

Kind: global function
Returns: Object - filtered object

Param Type Description
hash Object object or array to filter
test_function function a function which is called on keys/values

objClean(obj) ⇒

removes the following from deeply nested objects:

  • null
  • undefined
  • {}
  • []

Kind: global function
Returns: cleaned object

Param Type
obj Object

objDefault(obj, defs) ⇒ Object

apply default props to an object; don't override values from source

Kind: global function
Returns: Object - an object which has defs props

Param Type Description
obj Object original object
defs Object props to add without overriding

objMatch(obj, source) ⇒ boolean

deep equality match for any two objects

Kind: global function
Returns: boolean - do objects match?

Param Type
obj Object
source Object

clone(thing, [opts]) ⇒ Object

an efficient way to clone an Object; outpreforms JSON.parse(JSON.strigify()) by 100x

Kind: global function
Returns: Object - copied object

Param Type Description
thing Object object to clone
[opts] unknown

typecastInt(obj, [isClone]) ⇒ Object

visit every property of an object a turn "number" values into numbers

  • ex: {foo: {bar: '42'}} => {foo: {bar: 42}}

Kind: global function
Returns: Object - object with all "numbers" as proper numbers

Param Type Default Description
obj object object to traverse
[isClone] boolean false default false; if true will mutate the passed in object

awaitObj(obj) ⇒ Promise

utility to await object values

  • ex: {foo: await bar()}

Kind: global function
Returns: Promise - the resolved values of the object's keys

Param Type Description
obj object object

removeNulls(objWithNullOrUndef) ⇒ Object

explicitly remove keys with null or undefined values; mutates object

  • ex: {foo: "bar", baz: null} => {foo: "bar"}

Kind: global function
Returns: Object - an object without null or undefined values

Param Type Description
objWithNullOrUndef Object an object with null or undefined values

makeInteger(value) ⇒ number | NaN

check if a value is an integer, if so return it

Kind: global function
Returns: number | NaN - a number or NaN

Param Type Description
value string a value to test

dedupe(arrayOfThings) ⇒ Array.<any>

de-dupe array of objects w/Set, stringify, parse

Kind: global function
Returns: Array.<any> - deduped array

Param Type Description
arrayOfThings any array to dedupe

dedupeVal(arr, keyNames) ⇒ Array.<any>

de-dupe array of objects by value of specific keys

Kind: global function
Returns: Array.<any> - deduped array of objected

Param Type Description
arr Array.<any> array to dedupe
keyNames Array.<string> keynames to dedupe values on

chunk(sourceArray, chunkSize) ⇒ Array.<any>

chunk array of objects into array of arrays with each less than or equal to chunkSize

  • [{},{},{},{}] => [[{},{}],[{},{}]]

Kind: global function
Returns: Array.<any> - chunked array

Param Type Description
sourceArray Array.<any> array to batch
chunkSize number max length of each batch

shuffle(array, [mutate]) ⇒ Array.<any>

fisher-yates shuffle of array elements

Kind: global function
Returns: Array.<any> - shuffled array

Param Type Default Description
array Array.<any> array to shuffle
[mutate] boolean false mutate array in place? default: false

range(min, max, [step]) ⇒ Array.<number>

the classic python built-in for generating arrays of integers

Kind: global function
Returns: Array.<number> - a range of integers

Param Type Default Description
min number starting number
max number ending nunber
[step] number 1 step for each interval; default 1

deepFlat(arr) ⇒ Array.<any>

recursively and deeply flatten a nested array of objects

  • ex: [ [ [{},{}], {}], {} ] => [{},{},{},{}]

Kind: global function
Returns: Array.<any> - flat array

Param Type Description
arr Array.<any> array to flatten

strToArr(str) ⇒ Array.<string>

extract words from a string as an array

  • ex "foo bar baz" => ['foo','bar','baz']

Kind: global function
Returns: Array.<string> - extracted words

Param Type Description
str string string to extract from

attempt(fn, ...args)

try{} catch{} a function; return results

Kind: global function

Param Type
fn function
...args any

times(n, iteratee)

do a function N times

Kind: global function

Param Type Description
n number number of times
iteratee function function to run

throttle(func, wait, [options])

throttle a functions's execution every N ms

Kind: global function

Param Type Default Description
func function function to throttle
wait number ms to wait between executiations
[options] object {leading: true, trailing: false}

compose() ⇒ function

compose functions, left-to-right

  • ex: c(a,b,c) => a(b(c()))

Kind: global function
Returns: function - a composed chain of functions

id(any) ⇒ any

a function which returns it's value

Kind: global function
Returns: any - the same thing

Param Type Description
any any anything

cLog(data, message, [severity])

a cloud function compatible console.log()

Kind: global function

Param Type Default Description
data string | JSON data to log
message string accopanying message
[severity] string "`INFO`" google sev label; default INFO

log(item, [depth], [maxDepth]) ⇒ void

a comprehensive logging utility in all terminal environments

Kind: global function

Param Type Default Description
item any an item to log
[depth] number 0 depth to log
[maxDepth] number 100 maximum nested depth

progress(thing, p, message) ⇒ void

dumb progress bar; incrementing console message

  • ex: thing message #

Kind: global function

Param Type Description
thing string what is being
p number the number to show
message string -

time(label) ⇒ Timer

returns a timer with the following API

  • timer.start()
  • timer.end()
  • timer.report()
  • timer.prettyTime()

Kind: global function
Returns: Timer - a time

Param Type Description
label string name for timer

quickTime(callback)

a very quick way to check the length of a function; uses console.time

  • ex: timeTaken(main)

Kind: global function

Param Type
callback function

tracker([app], [token], [distinct_id]) ⇒ function

track stuff to mixpanel

  • ex: var t = track(); t('foo', {bar: "baz"})

Kind: global function
Returns: function - func with signature: (event, props = {}, cb = ()=>{})

Param Type Default Description
[app] string "'akTools'" value of $source prop
[token] string "&quot;99a1209a992b3f9fba55a293e211186a&quot;" mixpanel token
[distinct_id] string "os.userInfo().username" distinct_id

sleep(ms)

arbitrary sleep for N ms

Kind: global function

Param Type Description
ms number amount of time to sleep