a-toolbox
javascript lightweight basic tools for node.js and browser
Purpose
"This is my rifle. There are many others like it, but this one is mine."
Install
npm i a-toolbox --save
Quick start
const tools = toolsstring// > 'cut these brackets please'
modular import
const tools = string: fs:
On browser
API
array
array.remove(array, item)
- array <Array<*>>
- item <*>
remove an element from array it removes only the first occurrence
Example
let a = 'js''ruby''python'toolsarray// > a = ['js','python']
array.removeAt(array, index)
- array <Array<*>>
- index <number>
remove an element from array at position
Example
let a = 123toolsarray// > a = [2,3]
array.last(array)
- array <Array<*>>
- return: * last element of the array or undefined
get last element of array or undefined
Example
toolsarray// > 3
array.at(array)
- array <Array<*>>
- return: * nth element of array; if negative, start from end: -1 = last element; undefined if missing
get nth element of array
Example
toolsarray// > 1
array.first(array)
- array <Array<*>>
- return: * first element of the array or undefined
get first element of array or undefined
Example
toolsarray// > 1
array.contains(array, item)
- array <Array<*>>
- item <*>
- return: boolean
check if array contains an element
Example
toolsarray// > true
array.insert(array, index, item)
- array <Array<*>>
- index <number>
- item <*>
insert an item into array at index position
Example
let a = 'john''alice''bob'toolsarray// > a = ['mary', 'john', 'alice', 'bob']
array.concat(arrays)
- arrays <...Array<*>> to chain
- return: Array<*> chained arrays
concat arrays
Example
toolsarray// > [0,1,2,3,4,5]
array.empty()
empty array - need to keep references
Example
let a = 012toolsarray// > a = []
array.add(array, item, [unique=false])
- array <Array<*>>
- item <*>
- [unique=false] <boolean>
push item into array, optionally check if already exists
Example
let a = 0123toolsarray// > a = [0,1,2,3]
array.flat(array)
- array <Array<*>>
- return: Array<*> flatten array
creates a new array with all sub-array elements concatted into it recursively like Array.prototype.flatten()
Example
let a = 0123 >toolsarray// > [0,1,2,3]
array.sortingInsert(array_, item)
- array_ <Array<*>>
- item <*>
insert an element in a sorted array, keeping sorted
Example
let a = 012101120toolsarray// > a = [0,1,2,10,11,15,20]
array.binaryIndexOf(array, item)
-
array <Array<*>>
-
item <*>
-
return: number index of element of -1 like Array.indexOf but perform binary search (array should be sorted)
Example
toolsarray// > 0
fs
note: not available on browser
fs.exists(path)
- path <string> path
- return: Promise.<boolean> true if file or directory exists
replace deprecated fs.exists
Example
toolsfs// > true
fs.isFile(path)
- path <string> file path
- return: Promise.<boolean> true if it exists and is a file
Example
toolsfs// > true
fs.isDirectory(path)
- path <string> dir path
- return: Promise.<boolean> true if it exists and is a dir
Example
toolsfs// > true
fs.touch(path, [mode=0o666])
- path <string> file path
- [mode=0o666] <number>
- return: Promise.<void>
create an empty file if not exists
Example
toolsfs
fs.unlink(path, [safe=true])
- path <string> file path
- [safe=true] <boolean> if safe do not throw exception
- return: Promise.<void>
delete file, optionally in safe mode
Example
toolsfs
hash
hash.sha256(data)
- data <string> any string
- return: string sha256 in hex format
Generate hash using sha256 in hex format
Example
toolshash// > 'ee42f619919727584b66fe25248ed4bba8e87dcfb3e62a90143ea17ba48df58e'
object
object.flat(obj)
- obj <Object>
- return: Object
flat keys in object
Example
toolsobject// > { 'a.a1': 1, 'a.a2': 2, 'b': 3 }
object.merge(a, b)
- a <Object>
- b <Object>
merge b into a
Example
let a = a:1b:'ciao'toolsobject// > a = { a: 4, b: 'ciao', c: { d: 8, e: 9 } }
object.clone(obj)
- obj <Object|Array> The array or the object to clone
- return: Object|Array
Clone an array or an object in input
Example
toolsobject// > {a: 1, b: 'ciao'}
object.getKeys(obj)
- obj <Object>
- return: Array<string>
Example
toolsobject// > ['a','b','c']
object.inherits(destination, source)
- destination <Object>
- source <Object>
it use Object.getOwnPropertyNames
to inherits child from parent, without prototype
Example
let a = {}toolsobject// > a = {f0: () => { }, p1: 1, p2: 'ciao'}
object.empty(obj)
- obj <Object>
empty object - need to keep references
Example
let a = a:0b:1c:2d:e:f:-1toolsobject// > a = {}
object.raise(flat)
- flat <Object>
- return: Object
restore flat object
Example
toolsobject// > { a: { a1: 1, a2: 2 }, b: 3 }
object.getByFlatKey(obj, fkey)
- obj <Object>
- fkey <string>
- return: Object
get value in object using a flat key
Example
toolsobject// > 1 toolsobject// > 1
object.setByFlatKey(obj, fkey, val)
- obj <Object>
- fkey <string>
- val <*>
set value in object using a flat key
Example
let a = {}toolsobject// > a = { a: { b: {c: 1} } } let a = {}toolsobject// > a = { a: { b: [{c: 1}] } }
util
util.isSet(val)
- val <*>
- return: bool
check if val
is setted, means it's not null
or undefined
util.onBrowser()
- return: bool
check if you are on browser or not
string
string.template(str, obj, [remove=false])
- str <string>
- obj <Object>
- [remove=false] <boolean> remove missing placeholders from obj, default false
- return: string
replace placeholders inside graph brackets {} with obj dictionary ~ES6 template string without $
Example
toolsstring// > 'hi Alice how are you?'
string.trim(str, cuts)
- str <string>
- cuts <Array>
- return: string
trim string
Example
toolsstring// > 'regular trim'
string.replaceAll(str, from, to)
- str <string>
- from <string>
- to <string>
- return: string
Example
toolsstring// > 'bcdefg'
string.capitalize(str)
- str <string>
- return: string
Example
toolsstring// > 'Alice'
string.prependMissing(prefix, str)
- prefix <string>
- str <string>
- return: string
Example
toolsstring// > 'miss Alice'
random
random.rnd(max)
- max <number>
- return: number
get random int from 0 to max
Example
toolsrandom// > 5
random.number(min, max)
- min <number>
- max <number>
- return: number
get random int from min to max
Example
toolsrandom// > 11
random.string([length=8], [set=abcdefghijklmnopqrstuvwxyz])
- [length=8] <number>
- [set=abcdefghijklmnopqrstuvwxyz] <Array>
- return: string
get random string
Example
toolsrandom// > 'ajdsfchakwt'
random.hex([length=8])
- [length=8] <number>
- return: string
get random hex string
Example
toolsrandom// > '1bc956bf'
random.hash(salt)
- salt <?string>
- return: string
get random hash string
Example
toolsrandomhash// > '1f8a690b7366a2323e2d5b045120da7e93896f471f8a690b731f8a690b739ab5'
random.element(array, not)
- array <Array<*>>
- not <Array<*>>
- return: * element
get random element from array
Example
toolsrandom// > 1
sys
note: not available on browser
sys.isRoot()
- return: bool is root or not
check if running user is root
time
time.chrono.set([tag=chrono])
- [tag=chrono] <string>
start a timer identified by tag
Example
toolstimechrono
time.chrono.reset([tag=chrono])
- [tag=chrono] <string>
reset the timer identified by tag
Example
toolstimechrono
time.chrono.clear([tag=chrono])
- [tag=chrono] <string>
discard the timer identified by tag
Example
toolstimechronoclear'query'
time.chrono.get([tag=chrono])
- [tag=chrono] <string>
- return: number ms
get the timer in ms from start (or reset) identified by tag
Example
toolstimechrono// > 11
time.gc()
clear timers (if you care about memory)
task
class task.Worker(options)
- options <Object>
- options.done <function> callback when all tasks are completed simple parallel tasks manager
Example
const tasks = { console } const _asyncOperationTimeout = 500 1000 200 1500 100; for const i in _asyncOperationTimeout _tasks; for const i in _asyncOperationTimeout ;
Worker.todo()
add task
Example
tasks
Worker.done()
declare task it's done
Example
tasks
event
class event.Emitter()
simple event emitter
Example
const emitter = emitter emitter emitteremitter emitter
Emitter.emit(name, ...values)
- name <string> event name
- ...values <*> values to pass to the event listener
emit an event
Example
event
Emitter.on(name, callback)
- name <string> event name
- callback <function>
listen to an event
Example
emitter
Emitter.once(name, callback)
- name <string> event name
- callback <function>
listen to an event only once
Example
emitter
Emitter.off(name)
- name <string> event name
stop listening to an event
Example
emitter
Changelog
v. 1.7.2
- add
object.getByFlatKey
support also Array
v. 1.7.1
- add
fs.isFile
andfs.isDirectory
v. 1.6.2
fs.exists
return true on files and directories, instead of only files
v. 1.5.1
string.template
support multi-level syntax object
v. 1.5.1
object.setByFlatKey
support also Array
v. 1.5.0
- add
event.Emitter
(simple event emitter, for browser)
v. 1.2.0
- use hash.js instead of
crypto
(for browser)
v. 1.0.0
- general review
- modular loader
- browser version
TODO
- string.caseCamel, string.casePascal
- object.walk test, doc
- travis CI / node, browser
- coverage badge / coverage 100%
License
The MIT License (MIT)
Copyright (c) 2015-2019, braces lab
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.