UNPKG

meows

Version:
529 lines (467 loc) 13.9 kB
## Utilities Only a very cool Shiba would even dare use a cat's tools. [Alternative Documentation WIP.](https://shiba-sama.github.io/utilities/docs/last.html) ### Installation & Usage ```bash npm -i meows yarn add meows ``` ```javascript import * as U from meows import { isType, isEmpty, notEmpty } from 'meows' ``` ```javascript const U = require('meows') const { isType, isEmpty, notEmpty } = require('meows') ``` ## Strings ```typescript const space = ' ' const spaces = /\s+/ const character = '' const alphabet = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ] /** Split string by spaces. */ function split_by_spaces(str: string): string[] /** Alphabetical character → prime number. */ function alpha_to_prime(alphabet: string): number /** * word anagram → prime product * * @description * An anagram is any rearrangement of a string. Conveniently, the product of * primes is the same regardless of order, and also allows us to count how many * of each prime was used, acting as an identity for anagrams. * * @example * anagram_to_id('listen') === anagram_to_id('silent') // => true * anagram_to_id('admirer') === anagram_to_id('married') // => true */ function anagram_to_id(word: string): number /** * Strips a string of all normal whitespaces. * @example * stripSpaces(' a b c ' ) // => 'abc' */ function stripSpaces(str:string): string ``` ## Date and Time ```typescript /** Convert an integer from 1 to 12 to a month. */ function number_to_month(integer: number): string /** A utility to store multiple timestamps for performance timing. */ class Timer { // The full state of the Timer object. _log(): { label: string, time: number }[] // A list of Unix timestamps. _times(): number[] // Add a midpoint to timer with optional label. next(label: string): void // Start timer with optional label. start(label: string): void // Add endpoint to timer with optional label. end(label: string): void // range :: () → integer || NaN if fewer than 2 timestamps. range(): number // delta :: () → integer[] delta(): number[] // Returns array of relative difference of time from start, unix timestamp as first entry. // relative :: () → integer[] relative(): number[] } ``` ## Error and Logging ```typescript /** Alias for `console.log()`. */ function log(...a: any[]): void /** `console.log()` with an introductory string message. */ function logStr(msg?: string, ...a: any[]): void /** * Log something to console with optional message, then returns identical input. * * @example * Promise.all(pending) * .then(x => logId(x, 'task: done')) * .then(sendTask) */ function logId(x: any, msg?:string): any ``` ## Arrays ```typescript /** * A function for quickly generating arrays populated by a range of integers, * with an optional skip interval. * * @example * range(3) // => [0, 1, 2, 3] * range(-3) // => [0, -1, -2, -3] * range(-2, 2) // => [-2, -1, 0, 1, 2] * range(2, -2) // => [2, 1, 0, -1, -2] * range(-10, 10, 5) // => [-10, -5, 0, 5, 10] * range(10, -10, 5) // => [10, 5, 0, -5, -10] */ function range(p0:number, pf?:number, speed?:number): number[] /** * Shallow filters out redundant members. * @example * uniques([0, 1, 2, 2, 3, 3]) // => [0, 1, 2, 3] */ function uniques(arr?: any[]): any[] /** * Shallow checks for repeat members. * @example * has_repeat([1, 2, 3]) // => false * has_repeat([1, 2, 1]) // => true */ function hasRepeat(arr: any[]): boolean /** * Choose random member in array. * @example * rand_choice([1, 'a', null]) // => 1 * rand_choice([1, 'a', null]) // => null */ function randChoose(arr?: any[]): any /** * Uses `λ` to populate an array of `size` length. * * @example * series(x => 0.5*x**2 + 0.5*x, 5) // => [0, 1, 3, 6, 10] */ function series(λ:Function, size:number): any[] /** * Returns a shallow copy of the last value of your array. The default behavior * is to return `undefined` on an empty array while `throwOnEmpty` is set to * `false`. * * @example * last([3, 2, 1]) // => 1 * last([3, 2, [1, 0]]) // => [1, 0] * last([null]) // => null * last([]) // => undefined if throwOnEmpty is false (!) */ function last(arr: any[], throwOnEmpty?: boolean): any ``` ## Objects ```typescript /** An empty object with no prototype. */ type ONULL = object /** Flip the binary value for a property on an object. */ function flipProp(prop: string, obj: object): object /** Merge objects with an empty object; can be used to strip prototype. */ function merge(...objs: object[]) /** Grab an object based on pathway of sequence of keys. * @example * const store = { * a: 0, * b: { * a: [0, 0, 0], * b: 1, * } * } * const node = path(store, 'a', 'b', 'a') * const value = node[0] * * node[0] = 1 * console.log(store.a.b.a) // => [1, 0, 0] * console.log(value * 2) // => 2 */ function path(obj: object, ...props: string[]): any ``` ## Functions ```typescript /** composes a sequence of functions from right to left. */ function compose(...fns: Function[]): Function /** composes a sequence of functions from left to right. */ function pipe(...fns: Function[]): Function /** zip, but with a function */ function zipWith(λ: Function, v1: any[], v2: any[]): any[] /** * @example * [true, true, false].filter(identity) // => [true, true] */ function identity(x: any): any /** * Given a lambda and a value `x`, run the lambda with optional arguments as a * side effect, and then return the original given value `x`. * * @example * function sayHi(msg = 'hi') { console.log(msg) } * effectId(sayHi, 42) // => logs 'hi' and returns 42 * effectId(sayHi, 42, 'yo') // => logs 'yo' and returns 42 */ function effectId(λ:Function, x, ...args) /** * See if at least one array element * @example * const v1 = [2, 4, 6, 8] * const v2 = [2, 4, 6, 9] * const even = x => x % 2 === 0 * * count(even, v1) // => 4 * count(even, v2) // => 1 * count(even, []) // => 0 */ function count(λ: Function, arr: any[]): number | TypeError /** * Given λ → returns `(compose not λ)`. * @example * const notArray = not(Array.isArray) * notArray([]) // => false * notArray({}) // => true */ function not(λ: Function): (...args: any[]) => boolean /** * Checks if an array is a non-empty array of things that would always pass * your boolean function. Like `orMap` or `.every()` except empty arrays return * false. * * @example * always(even, [0, 2, 4]) // => true * always(even, [0, 1, 2]) // => false * always(even, []) // => false */ function always(cond: Function, arr: any[]): boolean /** * Coerces values to `true`. If input is a function, `truthy` will run the * function with optional arguments for side effects before returning `true`. * @example * truthy(console.log('hi')) && 42 // logs 'hi' and returns 42 * * const say = (msg='hi') => console.log(msg) * truthy(say) // logs 'hi' and returns true * truthy(say, 'yo') // logs 'yo' and returns true */ function truthy(λ: Function, ...arg: any[]): boolean /** * Coerces values to `false`. If input is a function, `falsy` will run the * function with optional arguments for side effects before returning `false` * * @example * falsy(console.log('hi')) || 42 // logs 'hi' and returns 42 * * const say = (msg='hi') => console.log(msg) * falsy(say) // logs 'hi' and returns false * falsy(say, 'yo') // logs 'yo' and returns false */ function falsy(λ: Function, ...arg: any[]): boolean ``` ## Numbers and Random ```typescript /** * A suite of random tools. * * @example * Rand.int() // => -42 * Rand.real() // => -42.42 * Rand.bool() ? 'heads' : 'tails' * Rand.sBool() ? 'heads' : 'tails' */ class Rand { static int(min?:number, max?:number): number static real(min?:number, max?:number): number /** * Returns a weak random boolean. */ static wBool(): boolean /** * Given natural `n` ⟶ returns `n` 'strong' random booleans. * @example * Rand.sBool() ? 'heads' : 'tails' * Rand.sBool(10).filter(x => x) */ static bool(natural: number): boolean } /** Generate an array of `n` strong random integers. */ function randomInts(n: number): number[] /** Sums numeric arguments. */ function sum(nums: number[]): number /** Multiplies numeric arguments. */ function product(nums: number[]): number /** Finds the difference in magnitude between two numbers. */ function diff_abs(a: number, b: number): number /** Finds the delta of unidimensional array of reals. */ function diff_nums(nums: number[]): number[] /** Converts an integer to an array of its digits. * @example * int_to_digits(123450) // => [1, 2, 3, 4, 5, 0] */ function int_to_digits(int:number, base?:number): number[] /** * Randomly signs a signable number. If the value isn't signable, return `NaN`. * @example * const backoff = (tries) => 2**tries + plus_or_minus(Math.random()) */ function plus_or_minus(num: number): number function negative(num: number): number function positive(num: number): number function flipSign(num: number): number ``` ## Logic and Types ```typescript class notEmpty { /** * @example * notEmpty.arr([]) // => false * notEmpty.arr({a: 1}) // => false */ static arr(x): boolean /** * @example * notEmpty.obj([1, 2]) // => false * notEmpty.obj({}) // => false */ static obj(x): boolean /** * @example * notEmpty.str(null) // => false * notEmpty.str('') // => false * notEmpty.obj(' ') // => true */ static str(x): boolean /** * @example * const empty = new Map() * const full = new Map().set('animal', 'cat') * * notEmpty.map(full) // => true * notEmpty.map(empty) // => false * notEmpty.map({}) // => false * notEmpty.map([]) // => false */ static map(x): boolean } /** * Class of static boolean functions for finding whether a value <is> an empty * instance of a type. */ class isEmpty { /** * @example * isEmpty.arr({}) // => false * isEmpty.arr([0]) // => false * isEmpty.arr([]) // => true */ static arr(x): boolean /** * @example * isEmpty.obj([]) // => false * isEmpty.obj({a: 1}) // => false * isEmpty.obj({}) // => true */ static obj(x): boolean /** * @example * isEmpty.str([]) // => false * isEmpty.str(' ') // => false * isEmpty.str('') // => true */ static str(x): boolean /** * @example * const empty = new Map() * const full = new Map().set('animal', 'cat') * * isEmpty.map(empty) // => true * isEmpty.map(full) // => false * isEmpty.map({}) // => false * isEmpty.map([]) // => false */ static map(x): boolean } /** * Class of static boolean functions for determining non-canonical subtypes in * JavaScript, such as reals or signable 'numbers'. * * @example * isType.num(1/0) // => false * isType.int(3.0) // => true * isType.real(3) // => true * isType.err(NaN) // => false */ class isType { /** Excludes NaN and Infinity! */ static num(x?): boolean /** Checks if number is positive integer, including 0. */ static nat(x?): boolean /** Only safe integers. */ static int(x?): boolean /** Check if value is a string. */ static str(x?): boolean /** Check if value is a function. */ static fn(x?): boolean /** * Any signable number including neutral 0, but excluding NaN and null. * @example * isType.signable(0) // => true * isType.signable(1/0) // => true * isType.signable(-5) // => true * isType.signable({}) // => false * isType.signable(NaN) // => false * isType.signable(null) // => false */ static signable(x?): boolean /** * Checks if value is an error object. * @example * isType.err(new TypeError()) // => true * isType.err({}) // => false * isType.err(null) // => false */ static err(x?): boolean /** * Checks if value is a negative number, excluding `0`, and `Infinity`. * @example * isType.neg(-2) // true * isType.neg(+2) // false * isType.neg(-0) // false (!) * isType.neg(-1/0) // false (!) * isType.neg([]) // false * isType.neg(NaN) // false */ static neg(x?): boolean /** * Checks if value is an instance of Map. * * @example * isType.map(new Map()) // => true * isType.map({}) // => false * isType.map([]) // => false */ static map(x?): boolean } /** * Returns the type of an unknown value as a lower-cased string. Type 'number' * is defined separately from 'infinity' and 'nan' because most functions on * numbers don't expect those types. * * @example * typeName(new Map) // => 'map' * typeName(void f()) // => 'undefined' * typeName(null) // => 'null' * typeName([]) // => 'array' * typeName({}) // => 'object' * typeName(/\s+/) // => 'regexp' * typeName(0 / 0) // => 'nan' * typeName(-1 / 0) // => 'infinity' * * const buffer = new ArrayBuffer(16) * const view = new Int16Array(buffer) * const err = new Error() * * typeName(err) // => 'error' * typeName(buffer) // => 'arraybuffer' * typeName(view) // => 'int16view' */ function typeName(x?: any): string ``` ## Async ```typescript /** * Promisified setTimeout that resolves to `<any>` or `<void>`. * @example * // logs 'hi' after delay * let hi = async () => await wait(4000, 'hi') * .then(console.log) */ function wait(ms?:number, resolveTo?:any): Promise <any> ```