yarn add usefuljs --use-pnp
import { ajax , arr_last } from 'usefuljs' // react
import { ajax } from "usefuljs/useful.modern.js" // svelte
// install node fetch first on nodejs
global.fetch = require("node-fetch") // if using node.js
const { ajax } = require("usefuljs") // node.js
Perform ajax request using the native fetch API
method : default = GET
url
data : (if using post or put method)
signal : AbortController().signal (optional)
headers : additional headers in Object format (optional)
cors : enable or disabled cors (boolean) (optional)
formdata : form data object (optional),if set to true, data object is ignored
fetcher : custom fetch (optional)
json : parse response as json (optional), by default set to true
jsonbody : auto json stringify body before sending (optional), by default set to true
ajax({url:'/api/users/list'}).then(res => console.log(res));
ajax({
method:'POST',
url:'/api/users/create',
data:{ username:'austin',password:'abcdef'}
}).then(res => console.log(res));
ajax({
method:'post',
url:'/api/verify',
heades: {token: "abc123"},
data: { username: "testuser"}
})
const controller = new AbortController();
const signal = this.controller.signal;
ajax({url:'/api/test',signal});
// -- when u want to abort the ajax requet --
controller.abort();
ajax({fetcher: this.fetch})
Same as ajax but uses xhr API instead of fetch API + doesn't have the signal parameter
Returns last element from an array
arr_last(array)
Removes an element from an array (by value)
arr_rm(arr,elem)
By default mutate is set to true If set to false, array will be returned instead of mutating the original array
arr_rm(arr,elem,false)
Removes an element from an array (by index)
arr_rm(arr,index)
By default mutate is set to true If set to false, array will be returned instead of mutating the original array
arr_rm(arr,index,false)
Similar to the php array_push method, it adds new element to array (if value doesn't exist in array)
array_push(arr,"foo")
bytes (int)
decimal places (int)
Bytes to human readable string
formatBytes(1024)
// returns "1 KB"
formatBytes(3241234,3)
// returns "3.091 MB"
Delta/Difference between 2 objects
let a = {x: 123,y:456,c:999}
let b = {x: 123,y:222,c:888}
diffObjs(a,b)
// returns [{y:456,c:999},{y:222,c:888}]
Add an element to the beginning of an array
prepend("foo",array)
Deduplicates array
arr_dedup([2,3,4,4,2,5,5]);
// returns [2, 3, 4, 5]
Replaces all matches in a string
replaceAll(string1,'find','replace')
Get distance from bottom of the page
getDistFromBottom()
Object into array
const a = {a:"123",b:"456",c:"789"};
obj2arr(a); // <-- this returns : ["123","456","789"]
Is the value an integer (parses string too)
isInt("1") // true
isInt(1) // true
isInt("1cd") // false
Does the string contain numbers only
isNum("222") // true
isNum("222/22") //false
split array into chunks of smaller arrays
arr_chunk([1,2,3,4,5,6],2); // <-- returns 3 arrays : [1,2] , [3,4] , [5,6]
arr_chunk([1,2,3,4,5,6],3); // <-- returns 2 arrays: [1,2,3] , [4,5,6]
Async version of foreach
await asyncForEach(arr, x => console.log(x))
sort array of object by object property value
- Supply this as the parameter of the array.sort() function *
name : key name
length : sort by length boolean (default = false)
reverse: boolean (default = false)
const a = [{number:1}, {number:2}];
a.sort(obj_sort('number',false,true)); // <- returns [{number:2}, {number:1}]
generates uuidv4
uuidv4();
generates a uid
unique_id()
generates a short uid
shortuid()
Find all matching values in 2 arrays
const a = [1,2,3];
const b = [4,5,6];
const c = [1,2,3];
matching_array(a,b); // returns []
matching_array(a,c); // returns [1,2,3]
Change property name of an object
obj_prop_rename(obj,'old','new')
Filters an object
obj_filter(obj, x => x === 'abc');
Filters an object by key name
obj_key_filter(obj, x => x === 'name');
Upper case first letter
ucfirst('foobar'); // returns Foobar
Pauses
sleep(1000); // <-- sleep for 1000 miliseconds
Filter out empty/NaN elements in array
f_arr(['a',NaN,22,null]); // returns ["a", 22]
Filter out null / undefined in object
k = {x:243,y:323421,uuu:null}
f_obj(k) // returns {x: 243, y: 323421}
Escape Double Quotes
const newstring = escape_dq(oldstring);
Escape HTML
const escaped = escape_HTML(html);
Generate random colour hexcode
const colour = colourgen();
Generate random number integer from range
intgen(1,5); // returns a random number from 1 to 5
Converts array of object to object of arrays
arrobj2objarr([{a:1,b:2,c:3},{a:5,b:2,c:9}]); // { a:[1,5] , b:[2,2] , c:[3,9] }
Converts an array of object to a big object (user specify the column to be used as key)
arrobj2obj([{a:1,b:2,c:3},{a:5,b:2,c:9}],"a"); // { 1: {a:1,b:2,c:3}, 5: {a:5,b:2,c:9} }
Convert string to hex code
hexCode("康健雜誌");
// "5eb7506596dc8a8c"
Convert Array JSON to csv
toCSV(arrJSON)
Crc32 hashes a value
crc32("abc")