diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 720bac7..4684f1e 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -45,7 +45,7 @@ jobs: - name: ⬆️ Upload coverage report uses: codecov/codecov-action@v1 release: - if: + if: ${{ github.repository == 'arcath/utils' && contains('refs/heads/master,refs/heads/beta,refs/heads/next,refs/heads/alpha', github.ref) && github.event_name == 'push' }} @@ -67,13 +67,13 @@ jobs: - name: 📚 Build Docs run: npm run document - - - name: 🚀 Deploy + + - name: 🚀 Deploy uses: JamesIves/github-pages-deploy-action@4.1.1 with: branch: gh-pages folder: docs - + - name: 🏗 Build run: npm run build @@ -92,4 +92,4 @@ jobs: ] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} \ No newline at end of file + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.husky.js b/.husky.js index 7c6d6c7..4ba52ba 100644 --- a/.husky.js +++ b/.husky.js @@ -1 +1 @@ -module.exports = {} \ No newline at end of file +module.exports = {} diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..12da03f --- /dev/null +++ b/.prettierignore @@ -0,0 +1,2 @@ +lib/ +coverage/ \ No newline at end of file diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 0000000..20bc417 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1 @@ +module.exports = require('./config/prettierrc') diff --git a/.vscode/settings.json b/.vscode/settings.json index f5a1c9d..d0d02c3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,4 +4,4 @@ "titleBar.activeBackground": "#08474E", "titleBar.activeForeground": "#F0FCFD" } -} \ No newline at end of file +} diff --git a/Readme.md b/Readme.md index 9b489d0..5c4ee2a 100644 --- a/Readme.md +++ b/Readme.md @@ -1,6 +1,8 @@ # Utils -[![codecov](https://codecov.io/gh/Arcath/utils/branch/master/graph/badge.svg?token=2R7fS9DBHW)](https://codecov.io/gh/Arcath/utils) [![buid status](https://img.shields.io/github/workflow/status/arcath/utils/validate?logo=github&style=flat-square)](https://github.com/arcath/utils/actions?query=workflow%3Avalidate) [![NPM](https://img.shields.io/npm/v/@arcath/utils.svg?style=flat-square)](https://www.npmjs.com/package/@arcath/utils) +[![codecov](https://codecov.io/gh/Arcath/utils/branch/master/graph/badge.svg?token=2R7fS9DBHW)](https://codecov.io/gh/Arcath/utils) +[![buid status](https://img.shields.io/github/workflow/status/arcath/utils/validate?logo=github&style=flat-square)](https://github.com/arcath/utils/actions?query=workflow%3Avalidate) +[![NPM](https://img.shields.io/npm/v/@arcath/utils.svg?style=flat-square)](https://www.npmjs.com/package/@arcath/utils) A collection of utility functions bundled into one easy to install library. @@ -16,4 +18,4 @@ yarn add @arcath/utils ## More -A full list of functions and classes can be found at https://utils.arcath.net \ No newline at end of file +A full list of functions and classes can be found at https://utils.arcath.net diff --git a/config/prettierrc.js b/config/prettierrc.js new file mode 100644 index 0000000..f47b6c7 --- /dev/null +++ b/config/prettierrc.js @@ -0,0 +1,19 @@ +module.exports = { + arrowParens: 'avoid', + bracketSpacing: false, + embeddedLanguageFormatting: 'auto', + endOfLine: 'lf', + htmlWhitespaceSensitivity: 'css', + insertPragma: false, + jsxBracketSameLine: false, + jsxSingleQuote: false, + printWidth: 80, + proseWrap: 'always', + quoteProps: 'as-needed', + requirePragma: false, + semi: false, + singleQuote: true, + tabWidth: 2, + trailingComma: 'none', + useTabs: false +} diff --git a/jest.config.js b/jest.config.js index cba6235..62e36bc 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,9 +1,9 @@ const configs = require('kcd-scripts/config') module.exports = Object.assign(configs.jest, { - "testMatch": ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"], - "transform": { - "^.+\\.tsx?$": "ts-jest" + testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'], + transform: { + '^.+\\.tsx?$': 'ts-jest' }, - "collectCoverage": true -}) \ No newline at end of file + collectCoverage: true +}) diff --git a/package.json b/package.json index 6497bac..fdba801 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "lint": "kcd-scripts lint", "build": "tsc", "document": "typedoc --out ./docs --entryPoints src/index.ts --name Utils --readme Readme.md && echo utils.arcath.net > ./docs/CNAME", - "validate": "kcd-scripts validate" + "validate": "kcd-scripts validate", + "format": "kcd-scripts format" }, "author": "Adam Laycock ", "license": "MIT", @@ -18,6 +19,7 @@ "@types/node": "^15.0.0", "jest": "^26.6.3", "kcd-scripts": "^10.0.0", + "prettier": "^2.2.1", "ts-jest": "^26.5.5", "typedoc": "^0.20.36", "typescript": "^4.2.4" diff --git a/src/classes/bit-mask.spec.ts b/src/classes/bit-mask.spec.ts index c0cec50..586202c 100644 --- a/src/classes/bit-mask.spec.ts +++ b/src/classes/bit-mask.spec.ts @@ -4,25 +4,16 @@ const READ = 'read' const WRITE = 'write' const EXECUTE = 'execute' -type Permission = - typeof EXECUTE | - typeof READ | - typeof WRITE - - -const Bits: Permission[] = [ - READ, - WRITE, - EXECUTE -] +type Permission = typeof EXECUTE | typeof READ | typeof WRITE +const Bits: Permission[] = [READ, WRITE, EXECUTE] describe('BitMask', () => { it('should set values', () => { const mask = new BitMask(0, Bits) expect(mask.get(READ)).toBe(false) - + mask.set(READ, true) mask.set(READ, true) @@ -58,10 +49,10 @@ describe('BitMask', () => { expect(mask.value).toBe(0) //eslint-disable-next-line - expect((mask as any).get('test')).toBe(false); + expect((mask as any).get('test')).toBe(false) //eslint-disable-next-line - (mask as any).set('test') + ;(mask as any).set('test') expect(mask.value).toBe(0) }) -}) \ No newline at end of file +}) diff --git a/src/classes/bit-mask.ts b/src/classes/bit-mask.ts index 3d98c76..edacf2c 100644 --- a/src/classes/bit-mask.ts +++ b/src/classes/bit-mask.ts @@ -3,44 +3,44 @@ /** * Bit Masker utility class. */ -export class BitMask{ +export class BitMask { /** The current value of the mask */ value: number bits: T[] /** - * + * * @param value The current value of the bit mask, defaults to `0` * @param bits The array of names to use e.g. `['canOpen', 'canClose']` */ - constructor(value: number = 0, bits: T[] = []){ + constructor(value: number = 0, bits: T[] = []) { this.value = value this.bits = bits } - _get(bit: number){ + _get(bit: number) { return !!((1 << bit) & this.value) } - _set(bit: number, value: boolean){ - if(value){ - if(!this._get(bit)){ + _set(bit: number, value: boolean) { + if (value) { + if (!this._get(bit)) { this.value = (1 << bit) ^ this.value } - }else if(this._get(bit)){ + } else if (this._get(bit)) { this.value = (1 << bit) ^ this.value } } /** * Checks the given bit name for its boolean value. - * + * * @param name The name of the bit to check. e.g. `canOpen` */ - get(name: T){ + get(name: T) { const index = this.bits.indexOf(name) - if(index !== -1){ + if (index !== -1) { return this._get(index) } @@ -49,20 +49,20 @@ export class BitMask{ /** * Sets the given bit to the supplied value. - * + * * @param name The name of the bit to set e.g. `canClose` * @param value The boolean value to set it to. */ - set(name: T, value: boolean){ + set(name: T, value: boolean) { const index = this.bits.indexOf(name) - - if(index !== -1){ + + if (index !== -1) { this._set(index, value) } } - asArray(){ - return this.bits.filter((bit) => { + asArray() { + return this.bits.filter(bit => { return this.get(bit) }) } @@ -70,24 +70,24 @@ export class BitMask{ /** * Returns an array of indexes in the bits array that are currently true. */ - asIndexArray(){ - return this.asArray().map((bit) => { + asIndexArray() { + return this.asArray().map(bit => { return this.bits.indexOf(bit) }) } /** * Sets all values in the mask to true if they are in the array and false if they are not. - * + * * @param indexs An array of indexes in the bits array that need to be true.1 */ - fromIndexArray(indexs: number[]){ + fromIndexArray(indexs: number[]) { this.bits.forEach((bit, index) => { - if(indexs.includes(index)){ + if (indexs.includes(index)) { this.set(bit, true) - }else{ + } else { this.set(bit, false) } }) } -} \ No newline at end of file +} diff --git a/src/classes/logger.spec.ts b/src/classes/logger.spec.ts index 8d2ac02..1c47f2e 100644 --- a/src/classes/logger.spec.ts +++ b/src/classes/logger.spec.ts @@ -1,25 +1,25 @@ /* eslint no-control-regex:off */ import {Logger} from '../' -describe("Logger", () => { - it("should log messages", () => { +describe('Logger', () => { + it('should log messages', () => { console.log = jest.fn() const logger = new Logger() logger.log('foo') - expect((console.log as jest.Mock).mock.calls[0][0]).toContain("foo") + expect((console.log as jest.Mock).mock.calls[0][0]).toContain('foo') logger.log('bar', true) - expect((console.log as jest.Mock).mock.calls[1][0]).toContain("bar") + expect((console.log as jest.Mock).mock.calls[1][0]).toContain('bar') logger.error('widget') - expect((console.log as jest.Mock).mock.calls[2][0]).toContain("widget") + expect((console.log as jest.Mock).mock.calls[2][0]).toContain('widget') - const disabledLogger = new Logger('test', { output: false }) + const disabledLogger = new Logger('test', {output: false}) disabledLogger.log('nope') @@ -31,17 +31,17 @@ describe("Logger", () => { expect((console.log as jest.Mock).mock.calls).toHaveLength(3) }) - it("should set a service name", () => { + it('should set a service name', () => { console.log = jest.fn() const testLogger = new Logger('Service') testLogger.log('test') - expect((console.log as jest.Mock).mock.calls[0][0]).toContain("Service") + expect((console.log as jest.Mock).mock.calls[0][0]).toContain('Service') testLogger.error('error', true) - expect((console.log as jest.Mock).mock.calls[1][0]).toContain("Service") + expect((console.log as jest.Mock).mock.calls[1][0]).toContain('Service') }) }) diff --git a/src/classes/logger.ts b/src/classes/logger.ts index 1c90790..9622f24 100644 --- a/src/classes/logger.ts +++ b/src/classes/logger.ts @@ -2,19 +2,19 @@ import chalk from 'chalk' import {defaults} from '../functions/defaults' -interface LoggerOptions{ +interface LoggerOptions { // If `false` no messages will be logged. output: boolean } /** Logger Class */ -export class Logger{ +export class Logger { serviceName: string time: [number, number] options: LoggerOptions /** Creates a new logger with the given service name. */ - constructor(serviceName = '', options: Partial = {}){ + constructor(serviceName = '', options: Partial = {}) { this.serviceName = serviceName this.options = defaults(options, { @@ -24,19 +24,20 @@ export class Logger{ this.time = process.hrtime() } - private message(message: string, color: chalk.Chalk, timed: boolean){ + private message(message: string, color: chalk.Chalk, timed: boolean) { let m = color(`[${this.timeString()}]`) - if(this.serviceName !== ''){ + if (this.serviceName !== '') { m += color(`[${this.serviceName}]`) } m += ` ${message}` - - if(timed){ + if (timed) { const diff = process.hrtime(this.time) - m += chalk.yellow(` +${((diff[0] * 1e9 + diff[1]) / 1e9).toLocaleString('en-GB')}s`) + m += chalk.yellow( + ` +${((diff[0] * 1e9 + diff[1]) / 1e9).toLocaleString('en-GB')}s` + ) this.time = process.hrtime() } @@ -44,28 +45,32 @@ export class Logger{ return m } - log(message: string, timed = false){ - if(this.options.output) console.log(this.message(message, chalk.green, timed)) + log(message: string, timed = false) { + if (this.options.output) + console.log(this.message(message, chalk.green, timed)) } - error(message: string, timed = false){ - if(this.options.output) console.log(this.message(message, chalk.red, timed)) + error(message: string, timed = false) { + if (this.options.output) + console.log(this.message(message, chalk.red, timed)) } - private timeString(){ + private timeString() { const time = new Date() - //eslint-disable-next-line - return time.getDate().toString().padStart(2, '0') - + '-' - + time.getMonth().toString().padStart(2, '0') - + '-' - + time.getFullYear() - + ' ' - + time.getHours().toString().padStart(2, '0') - + ':' - + time.getMinutes().toString().padStart(2, '0') - + ':' - + time.getSeconds().toString().padStart(2, '0') + return ( + //eslint-disable-next-line + time.getDate().toString().padStart(2, '0') + + '-' + + time.getMonth().toString().padStart(2, '0') + + '-' + + time.getFullYear() + + ' ' + + time.getHours().toString().padStart(2, '0') + + ':' + + time.getMinutes().toString().padStart(2, '0') + + ':' + + time.getSeconds().toString().padStart(2, '0') + ) } } diff --git a/src/functions/async-for-each.spec.ts b/src/functions/async-for-each.spec.ts index 85e8e0f..33ce9d2 100644 --- a/src/functions/async-for-each.spec.ts +++ b/src/functions/async-for-each.spec.ts @@ -2,34 +2,42 @@ import {asyncForEach} from '../' describe('Async For Each (in sequence)', () => { it('should work async', async () => { - const array = [1,2,3] + const array = [1, 2, 3] const newArray: number[] = [] - await asyncForEach(array, (n, i) => { - return new Promise((resolve) => { - setTimeout(() => { - newArray[i] = n + 1 - resolve() - }, 100) - }) - }, {inSequence: true}) + await asyncForEach( + array, + (n, i) => { + return new Promise(resolve => { + setTimeout(() => { + newArray[i] = n + 1 + resolve() + }, 100) + }) + }, + {inSequence: true} + ) - expect(newArray).toStrictEqual([2,3,4]) + expect(newArray).toStrictEqual([2, 3, 4]) }) it('should work async (not in sequence)', async () => { - const array = [1,2,3] + const array = [1, 2, 3] const newArray: number[] = [] - await asyncForEach(array, (n, i) => { - return new Promise((resolve) => { - setTimeout(() => { - newArray[i] = n + 1 - resolve() - }, 100) - }) - }, {inSequence: false}) + await asyncForEach( + array, + (n, i) => { + return new Promise(resolve => { + setTimeout(() => { + newArray[i] = n + 1 + resolve() + }, 100) + }) + }, + {inSequence: false} + ) - expect(newArray).toStrictEqual([2,3,4]) + expect(newArray).toStrictEqual([2, 3, 4]) }) -}) \ No newline at end of file +}) diff --git a/src/functions/async-for-each.ts b/src/functions/async-for-each.ts index 0a9c932..863f5b6 100644 --- a/src/functions/async-for-each.ts +++ b/src/functions/async-for-each.ts @@ -1,7 +1,7 @@ import {DeepPartial} from '../types' import {defaults} from './defaults' -interface AsyncForEachOptions{ +interface AsyncForEachOptions { /** Use the legacy style for look for itterations, when false this is a wrapper for `Promise.all` * Defaults to `false` */ @@ -14,16 +14,22 @@ const defaultOptions: AsyncForEachOptions = { /** * Runs the supplied itterator for all elements in the array asyncronously. - * + * * @param array The array to itterate through. * @param itterator The async function to run for each element. */ -export const asyncForEach = async (array: T[], itterator: (value: T, index: number, array: T[]) => Promise, options?: DeepPartial): Promise => { +export const asyncForEach = async ( + array: T[], + itterator: (value: T, index: number, array: T[]) => Promise, + options?: DeepPartial +): Promise => { const {inSequence} = defaults(options, defaultOptions) - if(inSequence){ - console.warn('in sequence is going to be removed in the future, for 0.x it is default on, soon it will change to default off.') - for(let index =0; index < array.length; index++){ + if (inSequence) { + console.warn( + 'in sequence is going to be removed in the future, for 0.x it is default on, soon it will change to default off.' + ) + for (let index = 0; index < array.length; index++) { //eslint-disable-next-line await itterator(array[index], index, array) } @@ -38,4 +44,4 @@ export const asyncForEach = async (array: T[], itterator: (value: T, index: n }) await Promise.all(promises) -} \ No newline at end of file +} diff --git a/src/functions/async-map.spec.ts b/src/functions/async-map.spec.ts index d88e9ff..6e39e6d 100644 --- a/src/functions/async-map.spec.ts +++ b/src/functions/async-map.spec.ts @@ -2,14 +2,14 @@ import {asyncMap} from '../' describe('Async Map', () => { it('should work async', async () => { - const array = [1,2,3] + const array = [1, 2, 3] - const newArray = await asyncMap(array, (n) => { - return new Promise((resolve) => { + const newArray = await asyncMap(array, n => { + return new Promise(resolve => { setTimeout(() => resolve(n + 1), 1000) }) }) - expect(newArray).toStrictEqual([2,3,4]) + expect(newArray).toStrictEqual([2, 3, 4]) }) -}) \ No newline at end of file +}) diff --git a/src/functions/async-map.ts b/src/functions/async-map.ts index 1078bab..8f4bf53 100644 --- a/src/functions/async-map.ts +++ b/src/functions/async-map.ts @@ -1,9 +1,12 @@ /** * Runs Array.map asyncronously. - * + * * @param list The array to map * @param executor The function to run for each */ -export const asyncMap = async (list: T[], executor: (element: T, index: number, array: T[]) => Promise): Promise => { +export const asyncMap = async ( + list: T[], + executor: (element: T, index: number, array: T[]) => Promise +): Promise => { return Promise.all(list.map(executor)) -} \ No newline at end of file +} diff --git a/src/functions/cache-for.spec.ts b/src/functions/cache-for.spec.ts index bc9b3b5..538ad9f 100644 --- a/src/functions/cache-for.spec.ts +++ b/src/functions/cache-for.spec.ts @@ -1,4 +1,11 @@ -import {cacheForSync, cacheFor, expireKey, cacheKey, resetCache, cacheKeyExists} from '../' +import { + cacheForSync, + cacheFor, + expireKey, + cacheKey, + resetCache, + cacheKeyExists +} from '../' jest.setTimeout(20000) @@ -19,11 +26,11 @@ describe('Cache For', () => { expect(value).toBe(2) expect(getValue()).toBe(2) - await new Promise((resolve) => { + await new Promise(resolve => { setTimeout(() => { expect(getValue()).toBe(3) expect(getValue()).toBe(3) - + expireKey(key) expect(getValue()).toBe(4) @@ -34,12 +41,12 @@ describe('Cache For', () => { }) it('should cache a value asyncrousnly', async () => { - const key = "testing" + const key = 'testing' let n = 1 const getValue = async () => { return cacheFor({key, duration: 1000}, () => { - return new Promise((resolve) => { + return new Promise(resolve => { n += 1 resolve(n) @@ -52,10 +59,10 @@ describe('Cache For', () => { expect(value).toBe(2) expect(await getValue()).toBe(2) - await new Promise((resolve) => { + await new Promise(resolve => { setTimeout(() => { //eslint-disable-next-line - getValue().then((v) => { + getValue().then(v => { expect(v).toBe(3) resolve(1) }) @@ -90,9 +97,7 @@ describe('Cache For', () => { }) it('should only run the function once', () => { - const mockFn = jest - .fn() - .mockReturnValue(10) + const mockFn = jest.fn().mockReturnValue(10) cacheKey('no-calls', () => mockFn()) @@ -103,4 +108,4 @@ describe('Cache For', () => { expect(mockFn).toHaveBeenCalledTimes(1) }) -}) \ No newline at end of file +}) diff --git a/src/functions/cache-for.ts b/src/functions/cache-for.ts index 5096990..c353c55 100644 --- a/src/functions/cache-for.ts +++ b/src/functions/cache-for.ts @@ -5,7 +5,7 @@ const cache: {[key: string]: any} = {} const timeouts: NodeJS.Timeout[] = [] -interface CacheForOptions{ +interface CacheForOptions { /** A key to store this value under */ key: string @@ -15,7 +15,7 @@ interface CacheForOptions{ /** * Does the supplied key exist in the cache? - * + * * @param key Key to check. */ export const cacheKeyExists = (key: string): boolean => { @@ -24,12 +24,12 @@ export const cacheKeyExists = (key: string): boolean => { /** * Cache the given value in the supplied key if the key doesn't already exist. - * + * * @param key The key to store. * @param value The value to store. */ export const cacheKey = (key: string, generator: () => T): T => { - if(!cacheKeyExists(key)){ + if (!cacheKeyExists(key)) { cache[key] = generator() } @@ -38,7 +38,7 @@ export const cacheKey = (key: string, generator: () => T): T => { /** * Delete the supplied key from the cache. - * + * * @param key Key to delete. */ export const expireKey = (key: string) => { @@ -50,29 +50,35 @@ export const expireKey = (key: string) => { * Removes all keys from the cache. */ export const resetCache = () => { - Object.keys(cache).forEach((key) => { + Object.keys(cache).forEach(key => { expireKey(key) }) - timeouts.forEach((timeout) => { + timeouts.forEach(timeout => { clearTimeout(timeout) }) } /** * A crude caching system that will cache values for the given time. - * + * * @param options See `CacheForOptions`. * @param generator The function that returns the cached value. */ - export const cacheForSync = ({key, duration}: CacheForOptions, generator: () => T): T => { - if(!cacheKeyExists(key)){ +export const cacheForSync = ( + {key, duration}: CacheForOptions, + generator: () => T +): T => { + if (!cacheKeyExists(key)) { cacheKey(key, () => generator()) timeouts.push( - setTimeout(() => { - expireKey(key) - }, (duration ? duration : minutesInMs(5))) + setTimeout( + () => { + expireKey(key) + }, + duration ? duration : minutesInMs(5) + ) ) } @@ -81,16 +87,19 @@ export const resetCache = () => { /** * A crude caching system that will cache values for the given time. - * + * * @param options See `CacheForOptions`. * @param generator The promise function that returns the cached value. */ - export const cacheFor = async ({key, duration}: CacheForOptions, generator: () => Promise): Promise => { - if(!cacheKeyExists(key)){ +export const cacheFor = async ( + {key, duration}: CacheForOptions, + generator: () => Promise +): Promise => { + if (!cacheKeyExists(key)) { const value = await generator() return cacheForSync({key, duration}, () => value) } return cache[key] -} \ No newline at end of file +} diff --git a/src/functions/create-map.spec.ts b/src/functions/create-map.spec.ts index 49cb92d..15259e1 100644 --- a/src/functions/create-map.spec.ts +++ b/src/functions/create-map.spec.ts @@ -18,6 +18,6 @@ describe('Create Map', () => { t2.setRange(2, 4, 2, 4, true) - expect(t2.get(3,4)).toBe(true) + expect(t2.get(3, 4)).toBe(true) }) -}) \ No newline at end of file +}) diff --git a/src/functions/create-map.ts b/src/functions/create-map.ts index 967478d..6cdcbca 100644 --- a/src/functions/create-map.ts +++ b/src/functions/create-map.ts @@ -1,24 +1,36 @@ -export interface Map{ +export interface Map { /** Get the value at position X,Y */ get(x: number, y: number): T /** Set the value of X,Y to `value` */ set(x: number, y: number, value: T): void /** Set all the cells in the range to `value` */ - setRange(minX: number, maxX: number, minY: number, maxY: number, value: T): void + setRange( + minX: number, + maxX: number, + minY: number, + maxY: number, + value: T + ): void /** The underlying map. Be warned this map maybe shifted so that 0 = minX etc... */ map: T[][] } /** * Create a co-ordinate grid - * + * * @param maxX The maximum X value. * @param maxY The maximum Y value. * @param initialValue THe default value for all cells. * @param minX (Optional) The minimum X value, defaults to 0 * @param minY (Optional) The minimum Y value, defaults to 0 */ -export const createMap = (maxX: number, maxY: number, initialValue: T, minX = 0, minY = 0): Map => { +export const createMap = ( + maxX: number, + maxY: number, + initialValue: T, + minX = 0, + minY = 0 +): Map => { const map: T[][] = [] const translateX = (x: number) => { @@ -29,9 +41,9 @@ export const createMap = (maxX: number, maxY: number, initialValue: T, minX = return y - minY } - for(let y = minY; y <= maxY; y++){ + for (let y = minY; y <= maxY; y++) { map[translateY(y)] = [] - for(let x = minX; x <= maxX; x++){ + for (let x = minX; x <= maxX; x++) { map[translateY(y)][translateX(x)] = initialValue } } @@ -44,9 +56,15 @@ export const createMap = (maxX: number, maxY: number, initialValue: T, minX = map[translateY(y)][translateX(x)] = value } - const setRange = (lowX: number, highX: number, lowY: number, highY: number, value: T) => { - for(let y = lowY; y <= highY; y++){ - for(let x = lowX; x <= highX; x++){ + const setRange = ( + lowX: number, + highX: number, + lowY: number, + highY: number, + value: T + ) => { + for (let y = lowY; y <= highY; y++) { + for (let x = lowX; x <= highX; x++) { set(x, y, value) } } @@ -58,4 +76,4 @@ export const createMap = (maxX: number, maxY: number, initialValue: T, minX = setRange, map } -} \ No newline at end of file +} diff --git a/src/functions/css.spec.ts b/src/functions/css.spec.ts index a7393fe..36d446f 100644 --- a/src/functions/css.spec.ts +++ b/src/functions/css.spec.ts @@ -1,5 +1,15 @@ -import {pxToNumber, emToNumber, remToNumber, vhToNumber, vwToNumber, - numberToPx, numberToEm, numberToRem, numberToVh, numberToVw} from '../' +import { + pxToNumber, + emToNumber, + remToNumber, + vhToNumber, + vwToNumber, + numberToPx, + numberToEm, + numberToRem, + numberToVh, + numberToVw +} from '../' describe('CSS', () => { it('should conver units to numbers', () => { @@ -18,6 +28,5 @@ describe('CSS', () => { expect(numberToRem(90)).toBe('90rem') expect(numberToVh(56)).toBe('56vh') expect(numberToVw(32)).toBe('32vw') - }) -}) \ No newline at end of file +}) diff --git a/src/functions/css.ts b/src/functions/css.ts index 3fde986..9abc0bc 100644 --- a/src/functions/css.ts +++ b/src/functions/css.ts @@ -1,13 +1,13 @@ /** * Creates a function that turns `1unit` into `1` - * + * * @param regex The regex to remove the unit e.g. `/^([0-9\.]*?)px$/` */ const asNumber = (regex: RegExp) => { return (unit: string) => { const matches = regex.exec(unit) - if(!matches) return 0 + if (!matches) return 0 return parseFloat(matches[1]) } @@ -15,7 +15,7 @@ const asNumber = (regex: RegExp) => { /** * Creates a function to add a unit to the number. - * + * * @param unit The unit to append. */ const asUnit = (unit: string) => { @@ -44,4 +44,4 @@ export const numberToRem = asUnit('rem') /** Conver a number to vh */ export const numberToVh = asUnit('vh') /** Conver a number to vw */ -export const numberToVw = asUnit('vw') \ No newline at end of file +export const numberToVw = asUnit('vw') diff --git a/src/functions/defaults.spec.ts b/src/functions/defaults.spec.ts index a89ba7f..5ab4698 100644 --- a/src/functions/defaults.spec.ts +++ b/src/functions/defaults.spec.ts @@ -56,4 +56,4 @@ describe('Defaults', () => { expect(results.test).toBe(true) }) -}) \ No newline at end of file +}) diff --git a/src/functions/defaults.ts b/src/functions/defaults.ts index d9c23c2..8092e1a 100644 --- a/src/functions/defaults.ts +++ b/src/functions/defaults.ts @@ -2,18 +2,21 @@ import {DeepPartial} from '../types' /** * Deeply applies defaults to an object. - * + * * @param supplied The supplied options, a `DeepPartial` of `defaultValues`. * @param defaultValues The default values to fallback on. Should represent a full copy of the options object. */ -export const defaults = (supplied: DeepPartial | undefined, defaultValues: T) => { +export const defaults = ( + supplied: DeepPartial | undefined, + defaultValues: T +) => { const result: T = {...defaultValues} - Object.keys(supplied ?? {}).forEach((key) => { - if(typeof (defaultValues as {[key: string]: string})[key] === 'object'){ - (result as {[key: string]: string})[key] = defaults( + Object.keys(supplied ?? {}).forEach(key => { + if (typeof (defaultValues as {[key: string]: string})[key] === 'object') { + ;(result as {[key: string]: string})[key] = defaults( //eslint-disable-next-line - (supplied as any)[key], + (supplied as any)[key], (defaultValues as {[key: string]: string})[key] ) @@ -21,8 +24,8 @@ export const defaults = (supplied: DeepPartial | undefined, def } //eslint-disable-next-line - (result as {[key: string]: string})[key] = (supplied as any)[key] + ;(result as {[key: string]: string})[key] = (supplied as any)[key] }) return result -} \ No newline at end of file +} diff --git a/src/functions/diff-array.spec.ts b/src/functions/diff-array.spec.ts index 230e946..6e7fc76 100644 --- a/src/functions/diff-array.spec.ts +++ b/src/functions/diff-array.spec.ts @@ -1,10 +1,10 @@ -import {diffArray} from '../' +import {diffArray} from '../' describe('diffArray', () => { it('should diff arrays', () => { const {additional, missing} = diffArray([1, 2, 3], [2, 4]) expect(additional).toStrictEqual([4]) - expect(missing).toStrictEqual([1,3]) + expect(missing).toStrictEqual([1, 3]) }) -}) \ No newline at end of file +}) diff --git a/src/functions/diff-array.ts b/src/functions/diff-array.ts index d6f2ee1..0ed736d 100644 --- a/src/functions/diff-array.ts +++ b/src/functions/diff-array.ts @@ -1,18 +1,21 @@ /** * Returns an object with 2 parameters. `additional` which is elements in `compare` that are not in `original`, and `missing` which are elements in `original` that are not in `compare` - * + * * @param original The base array to compare against * @param compare The array to compare to */ -export const diffArray = (original: T[], compare: T[]): { - additional: T[], +export const diffArray = ( + original: T[], + compare: T[] +): { + additional: T[] missing: T[] } => { - const missing = original.filter((value) => { + const missing = original.filter(value => { return !compare.includes(value) }) - const additional = compare.filter((value) => { + const additional = compare.filter(value => { return !original.includes(value) }) @@ -20,4 +23,4 @@ export const diffArray = (original: T[], compare: T[]): { additional, missing } -} \ No newline at end of file +} diff --git a/src/functions/diff-object.spec.ts b/src/functions/diff-object.spec.ts index 70afeb6..46b8062 100644 --- a/src/functions/diff-object.spec.ts +++ b/src/functions/diff-object.spec.ts @@ -19,6 +19,5 @@ describe('Diff Object', () => { expect(result.changed).toHaveLength(1) expect(result.added).toHaveLength(1) expect(result.removed).toHaveLength(1) - }) -}) \ No newline at end of file +}) diff --git a/src/functions/diff-object.ts b/src/functions/diff-object.ts index 5916907..307b052 100644 --- a/src/functions/diff-object.ts +++ b/src/functions/diff-object.ts @@ -1,35 +1,41 @@ -interface DiffObjectResult{ - added: (keyof K & keyof T)[], - changed: (keyof K & keyof T)[], +interface DiffObjectResult { + added: (keyof K & keyof T)[] + changed: (keyof K & keyof T)[] removed: (keyof K & keyof T)[] } -export const diffObject = (original: T, compare: K): DiffObjectResult => { - const result: DiffObjectResult = { +export const diffObject = ( + original: T, + compare: K +): DiffObjectResult => { + const result: DiffObjectResult = { added: [], changed: [], removed: [] } - Object.keys(original).forEach((key) => { - if(compare.hasOwnProperty(key)){ + Object.keys(original).forEach(key => { + if (compare.hasOwnProperty(key)) { // Key from Original exists in Compare - if((compare as {[key: string]: string})[key] !== (original as {[key: string]: string})[key]){ + if ( + (compare as {[key: string]: string})[key] !== + (original as {[key: string]: string})[key] + ) { //eslint-disable-next-line result.changed.push(key as any) } - }else{ + } else { //eslint-disable-next-line result.removed.push(key as any) } }) - Object.keys(compare).forEach((key) => { - if(!original.hasOwnProperty(key)){ + Object.keys(compare).forEach(key => { + if (!original.hasOwnProperty(key)) { //eslint-disable-next-line result.added.push(key as any) } }) return result -} \ No newline at end of file +} diff --git a/src/functions/grouped-by.spec.ts b/src/functions/grouped-by.spec.ts index 46203bb..9c3de69 100644 --- a/src/functions/grouped-by.spec.ts +++ b/src/functions/grouped-by.spec.ts @@ -21,4 +21,4 @@ describe('Grouped By', () => { expect(grouped[10]).toHaveLength(2) }) -}) \ No newline at end of file +}) diff --git a/src/functions/grouped-by.ts b/src/functions/grouped-by.ts index 66ebd0e..71f31e3 100644 --- a/src/functions/grouped-by.ts +++ b/src/functions/grouped-by.ts @@ -1,23 +1,26 @@ -export interface GroupedArray{ +export interface GroupedArray { [index: string]: T[] } /** * Takes an array of objects and returns an object with a property for each value in the `key` containing an array of all the objects that have that value. - * + * * @param key The key to group by. * @param array The array of objects. */ -export const groupedBy = (key: K, array: T[]): GroupedArray => { +export const groupedBy = ( + key: K, + array: T[] +): GroupedArray => { return array.reduce>((groups, value) => { //eslint-disable-next-line const k = value[key] as any //eslint-disable-next-line - if(!groups.hasOwnProperty(k)) groups[k] = [] + if (!groups.hasOwnProperty(k)) groups[k] = [] groups[k].push(value) return groups }, {}) -} \ No newline at end of file +} diff --git a/src/functions/indexed-by.spec.ts b/src/functions/indexed-by.spec.ts index 83ceece..a048c93 100644 --- a/src/functions/indexed-by.spec.ts +++ b/src/functions/indexed-by.spec.ts @@ -31,4 +31,4 @@ describe('Indexed By', () => { }) }).not.toThrowError('Key bob occurs more than once') }) -}) \ No newline at end of file +}) diff --git a/src/functions/indexed-by.ts b/src/functions/indexed-by.ts index b46dd64..c549821 100644 --- a/src/functions/indexed-by.ts +++ b/src/functions/indexed-by.ts @@ -1,10 +1,10 @@ import {defaults} from './defaults' -export interface IndexedArray{ +export interface IndexedArray { [index: string]: T } -export interface IndexedByOptions{ +export interface IndexedByOptions { collide: boolean } @@ -14,15 +14,12 @@ const defaultOptions: IndexedByOptions = { /** * Returns an object indexed by the given field from the array of objects. - * + * * @param key The key to index by. * @param array The array of Objects. * @param options See `IndexedByOptions` */ -export const indexedBy = < - T extends {}, - K extends keyof T ->( +export const indexedBy = ( key: K, array: T[], options: Partial = {} @@ -31,11 +28,12 @@ export const indexedBy = < return array.reduce>((indexedArray, value) => { //eslint-disable-next-line - if(!o.collide && indexedArray[(value[key] as any)]) throw new Error(`Key ${value[key]} occurs more than once`) + if (!o.collide && indexedArray[value[key] as any]) + throw new Error(`Key ${value[key]} occurs more than once`) //eslint-disable-next-line - indexedArray[(value[key] as any)] = value + indexedArray[value[key] as any] = value return indexedArray }, {}) -} \ No newline at end of file +} diff --git a/src/functions/keys.spec.ts b/src/functions/keys.spec.ts index 3643d7b..c9b0400 100644 --- a/src/functions/keys.spec.ts +++ b/src/functions/keys.spec.ts @@ -12,4 +12,4 @@ describe('Keys', () => { expect(k).toHaveLength(3) }) -}) \ No newline at end of file +}) diff --git a/src/functions/keys.ts b/src/functions/keys.ts index ddd1e63..7390e52 100644 --- a/src/functions/keys.ts +++ b/src/functions/keys.ts @@ -1,11 +1,11 @@ /** * Returns an array of keys that matches the type `keyof T` - * + * * @param object Any object. */ export const keys = (object: T): (keyof T)[] => { const objectKeys = Object.keys(object) //eslint-disable-next-line - return (objectKeys.filter((key) => object.hasOwnProperty(key)) as any) -} \ No newline at end of file + return objectKeys.filter(key => object.hasOwnProperty(key)) as any +} diff --git a/src/functions/map-property.spec.ts b/src/functions/map-property.spec.ts index 6ee5f81..9a30c87 100644 --- a/src/functions/map-property.spec.ts +++ b/src/functions/map-property.spec.ts @@ -17,4 +17,4 @@ describe('Map Property', () => { expect(names[0]).toBe('dave') }) -}) \ No newline at end of file +}) diff --git a/src/functions/map-property.ts b/src/functions/map-property.ts index a7e0c4c..58f6287 100644 --- a/src/functions/map-property.ts +++ b/src/functions/map-property.ts @@ -1,9 +1,12 @@ /** * Takes an array of objects and returns an array of values from the given `property` - * + * * @param array The array of objects * @param property The property to extract */ -export const mapProperty = (array: T[], property: K): T[K][] => { - return array.map((element) => element[property]) -} \ No newline at end of file +export const mapProperty = ( + array: T[], + property: K +): T[K][] => { + return array.map(element => element[property]) +} diff --git a/src/functions/nl2br.spec.ts b/src/functions/nl2br.spec.ts index f1d55b5..ea9cfc4 100644 --- a/src/functions/nl2br.spec.ts +++ b/src/functions/nl2br.spec.ts @@ -10,4 +10,4 @@ describe('NL2BR', () => { expect(withBreaks).toBe(`a test string
on two lines`) }) -}) \ No newline at end of file +}) diff --git a/src/functions/nl2br.ts b/src/functions/nl2br.ts index 88926b0..4dbdb9f 100644 --- a/src/functions/nl2br.ts +++ b/src/functions/nl2br.ts @@ -1,8 +1,8 @@ /** * Adds
for new lines in a string - * + * * @param string The multi line string to add
tags to */ export const nl2br = (string: string) => { - return string.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1
$2'); -} \ No newline at end of file + return string.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1
$2') +} diff --git a/src/functions/parameterize.spec.ts b/src/functions/parameterize.spec.ts index 10126bb..121f4d5 100644 --- a/src/functions/parameterize.spec.ts +++ b/src/functions/parameterize.spec.ts @@ -1,8 +1,10 @@ import {parameterize} from '../' -describe("Parameterize", () => { +describe('Parameterize', () => { it('should make strings safe for urls', () => { expect(parameterize("My Article's Title")).toBe('my-articles-title') - expect(parameterize("S0m3 Long $tring wITH odd (strange) chars in it...")).toBe('s0m3-long-tring-with-odd-strange-chars-in-it') + expect( + parameterize('S0m3 Long $tring wITH odd (strange) chars in it...') + ).toBe('s0m3-long-tring-with-odd-strange-chars-in-it') }) -}) \ No newline at end of file +}) diff --git a/src/functions/parameterize.ts b/src/functions/parameterize.ts index 70c8ea7..c5ab461 100644 --- a/src/functions/parameterize.ts +++ b/src/functions/parameterize.ts @@ -1,10 +1,13 @@ /** * Takes a string and makes it safe for url slugs. - * + * * For Example: `My Article's title` becomes `my-articles-title` - * + * * @param slug The string to parameterize */ export const parameterize = (slug: string): string => { - return slug.toLowerCase().replace(/[^a-zA-Z0-9 -]/g, "").replace(/\s/g, "-") -} \ No newline at end of file + return slug + .toLowerCase() + .replace(/[^a-zA-Z0-9 -]/g, '') + .replace(/\s/g, '-') +} diff --git a/src/functions/pick.spec.ts b/src/functions/pick.spec.ts index 94974a0..17450e6 100644 --- a/src/functions/pick.spec.ts +++ b/src/functions/pick.spec.ts @@ -8,16 +8,16 @@ describe('Pick & Omit', () => { c: 3 } - const picked = pick(o, ["a"]) + const picked = pick(o, ['a']) expect(picked).toHaveProperty('a') expect(picked).not.toHaveProperty('b') expect(picked.a).toBe(1) - const omitted = omit(o, ["a"]) + const omitted = omit(o, ['a']) expect(omitted).toHaveProperty('b') expect(omitted).not.toHaveProperty('a') expect(omitted.b).toBe(2) }) -}) \ No newline at end of file +}) diff --git a/src/functions/pick.ts b/src/functions/pick.ts index 4d93908..54121b4 100644 --- a/src/functions/pick.ts +++ b/src/functions/pick.ts @@ -3,7 +3,7 @@ import {keys} from './keys' /** * Pragmatic version of Typescripts `Pick - * + * * @param object The Object to pick fields from. * @param fields An array of fields to pick, * @returns An object with the picked fields. @@ -12,7 +12,10 @@ export const pick = < T extends {}, K extends (keyof T)[], P extends ArrayElement ->(object: T, fields: K): Pick => { +>( + object: T, + fields: K +): Pick => { //eslint-disable-next-line return fields.reduce((obj, field) => { //eslint-disable-next-line @@ -24,7 +27,7 @@ export const pick = < /** * Pragmatic version of Typescripts `Omit` - * + * * @param object The object to omit fields from. * @param fields The fields to omit. * @returns An object without the supplied fields. @@ -33,10 +36,13 @@ export const omit = < T extends {}, K extends (keyof T)[], P extends ArrayElement ->(object: T, fields: K): Omit => { +>( + object: T, + fields: K +): Omit => { //eslint-disable-next-line return keys(object).reduce((obj, field) => { - if(!fields.includes(field)){ + if (!fields.includes(field)) { obj[field] = object[field] } diff --git a/src/functions/range-as-string.spec.ts b/src/functions/range-as-string.spec.ts index d28eb2c..bbe7a88 100644 --- a/src/functions/range-as-string.spec.ts +++ b/src/functions/range-as-string.spec.ts @@ -2,13 +2,18 @@ import {rangeAsString, rangeAsArray} from '../' describe('Range As String', () => { it('should create strings', () => { - expect(rangeAsString([1,2,3])).toStrictEqual(['1-3']) - expect(rangeAsString([1,2,3,5])).toStrictEqual(['1-3','5']) - expect(rangeAsString([1,2,3,5,6])).toStrictEqual(['1-3','5,6']) - expect(rangeAsString([1,2,3,5,6,10,11,12,13,14,15])).toStrictEqual(['1-3','5,6','10-15']) + expect(rangeAsString([1, 2, 3])).toStrictEqual(['1-3']) + expect(rangeAsString([1, 2, 3, 5])).toStrictEqual(['1-3', '5']) + expect(rangeAsString([1, 2, 3, 5, 6])).toStrictEqual(['1-3', '5,6']) + expect( + rangeAsString([1, 2, 3, 5, 6, 10, 11, 12, 13, 14, 15]) + ).toStrictEqual(['1-3', '5,6', '10-15']) }) it('Should provide arrays', () => { - expect(rangeAsArray([1,2,3,5])).toStrictEqual([[1,3],[5,5]]) + expect(rangeAsArray([1, 2, 3, 5])).toStrictEqual([ + [1, 3], + [5, 5] + ]) }) -}) \ No newline at end of file +}) diff --git a/src/functions/range-as-string.ts b/src/functions/range-as-string.ts index f4eea47..d7caa3d 100644 --- a/src/functions/range-as-string.ts +++ b/src/functions/range-as-string.ts @@ -1,8 +1,8 @@ /** * Returns an array of ranges - * + * * e.g. `[[1,3], [5,6], [10,15], [20,20]]` - * + * * @param range An array of integers to describe */ export const rangeAsArray = (range: number[]): [number, number][] => { @@ -11,8 +11,8 @@ export const rangeAsArray = (range: number[]): [number, number][] => { }) const rangeArrays = sorted.reduce<[number, number][]>((ranges, n) => { - if(ranges.length === 0){ - ranges.push([n,n]) + if (ranges.length === 0) { + ranges.push([n, n]) return ranges } @@ -20,10 +20,10 @@ export const rangeAsArray = (range: number[]): [number, number][] => { const [, high] = ranges[i] - if(n === high + 1){ + if (n === high + 1) { ranges[i][1] = n - }else{ - ranges.push([n,n]) + } else { + ranges.push([n, n]) } return ranges @@ -34,17 +34,17 @@ export const rangeAsArray = (range: number[]): [number, number][] => { /** * Returns an array of string describing the range. - * + * * e.g. `['1-3','5,6','10-15','20']` - * + * * @param range An array of integers to describe */ - export const rangeAsString = (integers: number[]): string[] => { +export const rangeAsString = (integers: number[]): string[] => { const ranges = rangeAsArray(integers) - return ranges.map((range) => { - if(range[0] === range[1]) return `${range[0]}` - if(range[0] === range[1] - 1) return `${range[0]},${range[1]}` + return ranges.map(range => { + if (range[0] === range[1]) return `${range[0]}` + if (range[0] === range[1] - 1) return `${range[0]},${range[1]}` return `${range[0]}-${range[1]}` }) -} \ No newline at end of file +} diff --git a/src/functions/selectors.spec.ts b/src/functions/selectors.spec.ts index 0071716..84d8ae7 100644 --- a/src/functions/selectors.spec.ts +++ b/src/functions/selectors.spec.ts @@ -8,12 +8,12 @@ describe('Selectors', () => { {name: 'Phil', age: 30} ] - const filtered = propIs(items, "name", "Phil") + const filtered = propIs(items, 'name', 'Phil') expect(filtered).toHaveLength(1) - const notFiltered = propIsNot(items, "name", "Phil") + const notFiltered = propIsNot(items, 'name', 'Phil') expect(notFiltered).toHaveLength(2) }) -}) \ No newline at end of file +}) diff --git a/src/functions/selectors.ts b/src/functions/selectors.ts index 23091b2..f21f62f 100644 --- a/src/functions/selectors.ts +++ b/src/functions/selectors.ts @@ -1,25 +1,33 @@ /** * Find all entires in an array where `prop` equals `value`. - * + * * @param items The Items to filter * @param prop The property to filter * @param value The value to check for */ -export const propIs = (items: T[], prop: K, value: T[K]) => { - return items.filter((item) => { +export const propIs = ( + items: T[], + prop: K, + value: T[K] +) => { + return items.filter(item => { return item[prop] === value }) } /** * Find all entires in an array where `prop` does not equals `value`. - * + * * @param items The Items to filter * @param prop The property to filter * @param value The value to check for */ -export const propIsNot = (items: T[], prop: K, value: T[K]) => { - return items.filter((item) => { +export const propIsNot = ( + items: T[], + prop: K, + value: T[K] +) => { + return items.filter(item => { return item[prop] !== value }) -} \ No newline at end of file +} diff --git a/src/functions/time.spec.ts b/src/functions/time.spec.ts index eaec739..92a2e85 100644 --- a/src/functions/time.spec.ts +++ b/src/functions/time.spec.ts @@ -1,9 +1,22 @@ import { - msAsSeconds, msAsMinutes, msAsHour, - secondsInMs, secondsAsMinutes, secondsAsHours, - minutesInMs, minutesInSeconds, minutesAsHours, - hoursInMs, hoursInMinutes, hoursInSeconds, - SECOND_IN_MS, MINUTE_IN_SECONDS, MINUTE_IN_MS, HOUR_IN_MINUTES, HOUR_IN_SECONDS, HOUR_IN_MS + msAsSeconds, + msAsMinutes, + msAsHour, + secondsInMs, + secondsAsMinutes, + secondsAsHours, + minutesInMs, + minutesInSeconds, + minutesAsHours, + hoursInMs, + hoursInMinutes, + hoursInSeconds, + SECOND_IN_MS, + MINUTE_IN_SECONDS, + MINUTE_IN_MS, + HOUR_IN_MINUTES, + HOUR_IN_SECONDS, + HOUR_IN_MS } from '../' describe('Time FNS', () => { @@ -24,4 +37,4 @@ describe('Time FNS', () => { expect(secondsAsMinutes(60)).toBe(1) expect(secondsAsHours(HOUR_IN_SECONDS)).toBe(1) }) -}) \ No newline at end of file +}) diff --git a/src/functions/time.ts b/src/functions/time.ts index b403866..fd6d2e1 100644 --- a/src/functions/time.ts +++ b/src/functions/time.ts @@ -28,17 +28,37 @@ export const HOUR_IN_SECONDS = HOUR_IN_MINUTES * MINUTE_IN_SECONDS export const HOUR_IN_MS = HOUR_IN_SECONDS * SECOND_IN_MS export const msAsSeconds = divideBy(SECOND_IN_MS) -export const msAsMinutes = chain(divideBy(SECOND_IN_MS), divideBy(MINUTE_IN_SECONDS)) -export const msAsHour = chain(divideBy(SECOND_IN_MS), divideBy(MINUTE_IN_SECONDS), divideBy(HOUR_IN_MINUTES)) +export const msAsMinutes = chain( + divideBy(SECOND_IN_MS), + divideBy(MINUTE_IN_SECONDS) +) +export const msAsHour = chain( + divideBy(SECOND_IN_MS), + divideBy(MINUTE_IN_SECONDS), + divideBy(HOUR_IN_MINUTES) +) export const secondsInMs = multiplyBy(SECOND_IN_MS) export const secondsAsMinutes = divideBy(MINUTE_IN_SECONDS) -export const secondsAsHours = chain(divideBy(MINUTE_IN_SECONDS), divideBy(HOUR_IN_MINUTES)) +export const secondsAsHours = chain( + divideBy(MINUTE_IN_SECONDS), + divideBy(HOUR_IN_MINUTES) +) -export const minutesInMs = chain(multiplyBy(MINUTE_IN_SECONDS), multiplyBy(SECOND_IN_MS)) +export const minutesInMs = chain( + multiplyBy(MINUTE_IN_SECONDS), + multiplyBy(SECOND_IN_MS) +) export const minutesInSeconds = multiplyBy(MINUTE_IN_SECONDS) export const minutesAsHours = divideBy(HOUR_IN_MINUTES) -export const hoursInMs = chain(multiplyBy(HOUR_IN_MINUTES), multiplyBy(MINUTE_IN_SECONDS), multiplyBy(SECOND_IN_MS)) -export const hoursInSeconds = chain(multiplyBy(HOUR_IN_MINUTES), multiplyBy(MINUTE_IN_SECONDS)) -export const hoursInMinutes = multiplyBy(HOUR_IN_MINUTES) \ No newline at end of file +export const hoursInMs = chain( + multiplyBy(HOUR_IN_MINUTES), + multiplyBy(MINUTE_IN_SECONDS), + multiplyBy(SECOND_IN_MS) +) +export const hoursInSeconds = chain( + multiplyBy(HOUR_IN_MINUTES), + multiplyBy(MINUTE_IN_SECONDS) +) +export const hoursInMinutes = multiplyBy(HOUR_IN_MINUTES) diff --git a/src/functions/times.spec.ts b/src/functions/times.spec.ts index 7e87620..ee4364e 100644 --- a/src/functions/times.spec.ts +++ b/src/functions/times.spec.ts @@ -11,7 +11,7 @@ describe('Times', () => { expect(x).toBe(COUNT_TO) - const result = times(COUNT_TO, (i) => i) + const result = times(COUNT_TO, i => i) expect(result[COUNT_TO - 1]).toBe(COUNT_TO) expect(result).toHaveLength(COUNT_TO) @@ -27,9 +27,9 @@ describe('Times', () => { expect(x).toBe(COUNT_TO) - const result = await asyncTimes(COUNT_TO, async (i) => i) + const result = await asyncTimes(COUNT_TO, async i => i) expect(result[COUNT_TO - 1]).toBe(COUNT_TO) expect(result).toHaveLength(COUNT_TO) }) -}) \ No newline at end of file +}) diff --git a/src/functions/times.ts b/src/functions/times.ts index 0d5e234..436450f 100644 --- a/src/functions/times.ts +++ b/src/functions/times.ts @@ -2,13 +2,13 @@ import {asyncMap} from './async-map' /** * Repeat the given function `number` times - * + * * @param number The number of times to itterate * @param cb The function to run */ export const times = (number: number, cb: (i: number) => T): T[] => { const result: T[] = [] - for(let i = 1; i <= number; i++){ + for (let i = 1; i <= number; i++) { result.push(cb(i)) } @@ -17,16 +17,19 @@ export const times = (number: number, cb: (i: number) => T): T[] => { /** * Repeat the given function `number` times asyncronously - * + * * @param number The number of times to itterate * @param cb The function to run */ -export const asyncTimes = async (number: number, cb: (i: number) => Promise): Promise => { +export const asyncTimes = async ( + number: number, + cb: (i: number) => Promise +): Promise => { const numbers: number[] = [] - - for(let i = 1; i <= number; i++){ + + for (let i = 1; i <= number; i++) { numbers.push(i) } return asyncMap(numbers, cb) -} \ No newline at end of file +} diff --git a/src/functions/unique.spec.ts b/src/functions/unique.spec.ts index 43451c5..12a194c 100644 --- a/src/functions/unique.spec.ts +++ b/src/functions/unique.spec.ts @@ -2,15 +2,10 @@ import {unique} from '../' describe('Unique', () => { it('should find unique values', () => { - const samples = [ - 1, - 2, - 3, - 3, - ] + const samples = [1, 2, 3, 3] const uniqueSamples = unique(samples) expect(uniqueSamples).toHaveLength(samples.length - 1) }) -}) \ No newline at end of file +}) diff --git a/src/functions/unique.ts b/src/functions/unique.ts index ca72a24..eb4fdf9 100644 --- a/src/functions/unique.ts +++ b/src/functions/unique.ts @@ -1,16 +1,16 @@ /** * Returns an array of unique values from the given array. - * + * * @param array Array of values. */ export const unique = (array: T[]): T[] => { const result: T[] = [] - array.forEach((element) => { - if(!result.includes(element)){ + array.forEach(element => { + if (!result.includes(element)) { result.push(element) } }) return result -} \ No newline at end of file +} diff --git a/src/functions/value-or.spec.ts b/src/functions/value-or.spec.ts index 34a8629..18e1826 100644 --- a/src/functions/value-or.spec.ts +++ b/src/functions/value-or.spec.ts @@ -5,4 +5,4 @@ describe('ValueOr', () => { expect(valueOr(undefined, 'foo')).toBe('foo') expect(valueOr('bar', 'foo')).toBe('bar') }) -}) \ No newline at end of file +}) diff --git a/src/functions/value-or.ts b/src/functions/value-or.ts index ef642fb..89390e5 100644 --- a/src/functions/value-or.ts +++ b/src/functions/value-or.ts @@ -1,11 +1,11 @@ /** * Returns the supplied value if it is not undefined otherwise it returns the or value. - * + * * @param value The Value that could be undefined * @param or The fallback value */ export const valueOr = (value: T | undefined, or: T) => { - if(typeof value !== 'undefined') return value + if (typeof value !== 'undefined') return value return or -} \ No newline at end of file +} diff --git a/src/functions/wait-for.spec.ts b/src/functions/wait-for.spec.ts index d4ad179..525ae18 100644 --- a/src/functions/wait-for.spec.ts +++ b/src/functions/wait-for.spec.ts @@ -8,7 +8,7 @@ describe('waitFor', () => { const [result, error] = await waitFor(truthy()) - if(error){ + if (error) { throw error } @@ -16,7 +16,7 @@ describe('waitFor', () => { }) it('should return errors', async () => { - const e = new Error("FOO") + const e = new Error('FOO') const errors = async () => { throw e @@ -26,4 +26,4 @@ describe('waitFor', () => { expect(error).toBe(e) }) -}) \ No newline at end of file +}) diff --git a/src/functions/wait-for.ts b/src/functions/wait-for.ts index 2511604..2689029 100644 --- a/src/functions/wait-for.ts +++ b/src/functions/wait-for.ts @@ -1,16 +1,18 @@ -type WaitForResult = - [null, Error] | - [T, null] +type WaitForResult = [null, Error] | [T, null] /** * Normalises a promise that errors into an awaitable [result, error] array. - * + * * @param promise The resolveable promise */ -export const waitFor = async (promise: Promise): Promise> => { - return promise.then((result) => { - return [result, null] as [T, null] - }).catch((e) => { - return [null, e] - }) -} \ No newline at end of file +export const waitFor = async ( + promise: Promise +): Promise> => { + return promise + .then(result => { + return [result, null] as [T, null] + }) + .catch(e => { + return [null, e] + }) +} diff --git a/src/index.ts b/src/index.ts index be1a8c9..bd87f37 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,11 +3,26 @@ export {Logger} from './classes/logger' export {asyncForEach} from './functions/async-for-each' export {asyncMap} from './functions/async-map' -export {cacheFor, cacheForSync, expireKey, cacheKey, cacheKeyExists, resetCache} from './functions/cache-for' +export { + cacheFor, + cacheForSync, + expireKey, + cacheKey, + cacheKeyExists, + resetCache +} from './functions/cache-for' export {createMap, Map} from './functions/create-map' export { - pxToNumber, emToNumber, remToNumber, vhToNumber, vwToNumber, - numberToPx, numberToEm, numberToRem, numberToVh, numberToVw + pxToNumber, + emToNumber, + remToNumber, + vhToNumber, + vwToNumber, + numberToPx, + numberToEm, + numberToRem, + numberToVh, + numberToVw } from './functions/css' export {defaults} from './functions/defaults' export {diffArray} from './functions/diff-array' @@ -22,15 +37,28 @@ export {nl2br} from './functions/nl2br' export {parameterize} from './functions/parameterize' export {pick, omit} from './functions/pick' export { - msAsSeconds, msAsMinutes, msAsHour, - secondsInMs, secondsAsMinutes, secondsAsHours, - minutesInMs, minutesInSeconds, minutesAsHours, - hoursInMs, hoursInMinutes, hoursInSeconds, - SECOND_IN_MS, MINUTE_IN_SECONDS, MINUTE_IN_MS, HOUR_IN_MINUTES, HOUR_IN_SECONDS, HOUR_IN_MS + msAsSeconds, + msAsMinutes, + msAsHour, + secondsInMs, + secondsAsMinutes, + secondsAsHours, + minutesInMs, + minutesInSeconds, + minutesAsHours, + hoursInMs, + hoursInMinutes, + hoursInSeconds, + SECOND_IN_MS, + MINUTE_IN_SECONDS, + MINUTE_IN_MS, + HOUR_IN_MINUTES, + HOUR_IN_SECONDS, + HOUR_IN_MS } from './functions/time' export {times, asyncTimes} from './functions/times' export {unique} from './functions/unique' export {valueOr} from './functions/value-or' export {waitFor} from './functions/wait-for' -export {ArrayElement, DeepPartial} from './types' \ No newline at end of file +export {ArrayElement, DeepPartial} from './types' diff --git a/src/types.ts b/src/types.ts index 1fea088..c48034c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,13 +1,15 @@ /** * Turns array elements into a type. - * + * * `['name', 'email']` becomes `'name' | 'email'` */ -export type ArrayElement = ArrayType[number] +export type ArrayElement< + ArrayType extends readonly unknown[] +> = ArrayType[number] /** * Works the same as `Partial` except it applies `Partial` to sub elements. */ - export type DeepPartial = { +export type DeepPartial = { [P in keyof T]?: DeepPartial -} \ No newline at end of file +} diff --git a/tsconfig.eslint.json b/tsconfig.eslint.json index 0844f2f..7dae47f 100644 --- a/tsconfig.eslint.json +++ b/tsconfig.eslint.json @@ -1,7 +1,4 @@ { "extends": "./tsconfig.json", - "exclude": [ - "lib", - "node_modules" - ] -} \ No newline at end of file + "exclude": ["lib", "node_modules"] +} diff --git a/tsconfig.json b/tsconfig.json index 901ee24..8209afb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,15 +7,6 @@ "target": "es5", "declaration": true }, - "include": [ - "src/**/*.ts", - "src/**/*.d.ts", - "src/**/*.tsx" - ], - "exclude": [ - "lib", - "node_modules", - "src/**/*.spec.ts", - "src/**/*.spec.tsx" - ] -} \ No newline at end of file + "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx"], + "exclude": ["lib", "node_modules", "src/**/*.spec.ts", "src/**/*.spec.tsx"] +}