diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 53c37a1..0000000 --- a/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -dist \ No newline at end of file diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 04a7145..0000000 --- a/.eslintrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": ["@trantlabs/eslint-config-typescript"] -} \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 658558a..b3aa2db 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -38,3 +38,4 @@ jobs: # You can swap them out with your own user credentials. user_name: github-actions[bot] user_email: 41898282+github-actions[bot]@users.noreply.github.com + cname: mnjsf.trantlabs.com \ No newline at end of file diff --git a/.npmignore b/.npmignore index 9ff5eeb..6afb7ad 100644 --- a/.npmignore +++ b/.npmignore @@ -1,3 +1,5 @@ docs/ example/ -src/ \ No newline at end of file +src/ +.docusaurus +build \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 004de55..33fa3cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,66 @@ +## v2.0.0...v2.0.0 + +remove Object from package + +## v1.5.0 + + +### 🚀 Enhancements + + - **array):** Push random function (e27876e) + - **array:** InsertRandom & randomIndex (2967618) + - **array:** Use randomIndex within randomIndex (a1cebb8) + +### 🩹 Fixes + + - Exclude docs from npm package (cc70df9) + - **array:** Returning types (bd6e01d) + +### ❤️ Contributors + +- Conner Bachmann +- Samuel + +## v1.4.2 + + +### 🚀 Enhancements + + - **Date:** Add() and set() function (c641a90) + - Error handling for missing callbacks (7b828e3) + +### 🩹 Fixes + + - **Promise:** Make caught optional to fix prisma.io client (0daf28c) + - Deployment (634e3fb) + +### 🤖 CI + + - Deploy docs under http://mnjsf.trantlabs.com/ (6169e40) + +### ❤️ Contributors + +- Samuel + +## v1.4.0 + + +### 🚀 Enhancements + + - **date:** AddYear, addMonth, addDate, addHours, addMinutes, addSeconds, addMilliseconds (3d96c71) + +### 🩹 Fixes + + - **string:** Similarity (ffd75a8) + - **Promise:** Make caught optional to fix prisma.io client (0daf28c) + +### 🏡 Chore + + - Changelog (3749fc6) + +### ❤️ Contributors + +- Samuel ## v1.3.0 diff --git a/README.md b/README.md index 4ce9d42..2cf2852 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ mnjsf delivers functions missing from JavaScript This library extends the properties of `Array`, `Object`, `Promise`, `Global`, `Math`, `Number` and `String` -## [Documentation](https://trantlabs.github.io/missing-native-js-functions/) +## [Documentation](http://mnjsf.trantlabs.com/) ## Installation diff --git a/docusaurus.config.js b/docusaurus.config.js index 6413648..822c89f 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -8,10 +8,6 @@ const entryPoints = require("fs") .readdirSync(__dirname + "/src") .map((x) => __dirname + "/src/" + x); -const organizationName = "trantlabs"; -const projectName = "missing-native-js-functions"; -const githubUrl = `https://github.com/${organizationName}/${projectName}`; - /** @type {import('typedoc').TypeDocOptions} */ const typedoc = { tsconfig: __dirname + "/tsconfig.json", @@ -24,11 +20,9 @@ const typedoc = { const config = { title: "Missing Native JS Functions", tagline: "A zero-dependecy JavaScript utility library delivering missing native functions 💼", - url: `https://${organizationName}.github.io/`, - organizationName, - projectName, + url: `https://mnjsf.trantlabs.com/`, deploymentBranch: "gh-pages", - baseUrl: `/${projectName}/`, + baseUrl: `/`, onBrokenLinks: "throw", onBrokenMarkdownLinks: "warn", organizationName: "trantlabs", @@ -40,7 +34,6 @@ const config = { docs: { path: "./docs/", routeBasePath: "/", - editUrl: `${githubUrl}/edit/master/website`, }, }, ], diff --git a/example/Date.js b/example/Date.js index 6a70fee..ce562e9 100644 --- a/example/Date.js +++ b/example/Date.js @@ -2,3 +2,22 @@ require("../dist/Date"); console.log(Date.nowSeconds()); // -> 1613171021 + +console.log(new Date().isInPast("2021-02-12 12:00:00")); +// -> true + +console.log(new Date().setTimezone("UTC").getHours()); +// -> Current hour in UTC + +console.log(new Date().add({ year: 1, month: 1, date: 1, hours: 1, minutes: 1, seconds: 1, milliseconds: 1 })); +// -> All values of date are incremented by one + +console.log(new Date().set({ time: 0, hours: 12, utc: true })); +// -> 1970-01-01 12:00:00 UTC + +console.log(new Date().set({ time: 0, hours: 12 }).toLocaleString()); +// -> 1970-01-01 12:00:00 (Local time) + +console.log(new Date().addHours(1)); +// -> Current date time with one hour added +// -> 1674174846775 diff --git a/package.json b/package.json index 8bca77b..477217c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "missing-native-js-functions", - "version": "1.3.1", + "version": "2.0.0", "description": "mnJSf that should be the base library for every JS project", "main": "dist/index.js", "browser": "dist/mnjsf.min.js", @@ -39,7 +39,7 @@ "bugs": { "url": "https://github.com/trantlabs/missing-native-js-functions/issues" }, - "homepage": "https://trantlabs.github.io/missing-native-js-functions/", + "homepage": "http://mnjsf.trantlabs.com/", "devDependencies": { "@docusaurus/core": "2.2.0", "@docusaurus/module-type-aliases": "2.2.0", diff --git a/src/Array.ts b/src/Array.ts index 3f79dfd..151a348 100644 --- a/src/Array.ts +++ b/src/Array.ts @@ -11,7 +11,7 @@ define(Array.prototype, { }, insert: function (elem: T, index: number) { - if (!index) index = this.length; + if (index == null) index = this.length; this.splice(index, 0, elem); return this; }, @@ -33,7 +33,7 @@ define(Array.prototype, { }, unique: function (predicate?: (value: T, index: number, obj: T[]) => any) { - if (predicate) { + if (typeof predicate === "function") { return [ ...new Map( this.map((item: T, index: number, obj: T[]) => [predicate(item, index, obj), item]) @@ -47,6 +47,14 @@ define(Array.prototype, { return this[Math.floor(Math.random() * this.length)]; }, + randomIndex: function (): number { + return Math.floor(Math.random() * this.length); + }, + + insertRandom: function (elem: T): void { + this.insert(elem, this.randomIndex()); + }, + shuffle: function () { for (let i = this.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); @@ -55,7 +63,8 @@ define(Array.prototype, { return this; }, - findMap: function (predicate: (value: T, index: number, obj: T[]) => any | undefined): number { + findMap: function (predicate: (value: T, index: number, obj: T[]) => any | undefined): any { + if (typeof predicate !== "function") return for (let i = 0; i < this.length; i++) { const result = predicate(this[i], i, this); if (result) { @@ -65,6 +74,7 @@ define(Array.prototype, { }, findLast: function (predicate: (value: T, index: number, obj: T[]) => any | undefined): T | undefined { + if (typeof predicate !== "function") return for (let i = this.length; i >= 0; i--) { if (predicate(this[i], i, this)) return this[i]; } @@ -72,6 +82,7 @@ define(Array.prototype, { }, findLastIndex: function (predicate: (value: T, index: number, obj: T[]) => any | undefined): number { + if (typeof predicate !== "function") return -1 for (let i = this.length - 1; i >= 0; i--) { if (predicate(this[i], i, this)) return i; } @@ -197,6 +208,14 @@ declare global { * a.random() // 2 */ random(): T | undefined; + /** + * Inserts the element to a random position in the array, modifies original array + * @returns {T[]} array with inserted element + * @example + * let a = [1,2,3,4,5]; + * a.insertRandom(27) // a = [1,2,3,27,4,5] + */ + insertRandom(elem: T): void; /** * Returns the unique items of the array * @param {} predicate / condition @@ -256,6 +275,14 @@ declare global { * a.missing(b); // [1,2] */ missing(arr: T[]): T[]; + /** + * Returns a random Index of array + * @returns {number} Random Index + * @example + * let a = [1,2,3,4,5]; + * a.randomIndex() // 2 -> 3 + */ + randomIndex(): number; } } diff --git a/src/Date.ts b/src/Date.ts index f891e24..19a7ba6 100644 --- a/src/Date.ts +++ b/src/Date.ts @@ -6,19 +6,71 @@ define(Date, { }, }); +type DateSetOptions = { + time?: number; + year?: number; + month?: number; + date?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + utc?: boolean; + timezone?: string; +}; + define(Date.prototype, { setTimezone: function (this: Date, timezone: string) { - return new Date( - this.toLocaleString("en-US", { - timeZone: timezone, - }) + this.setTime( + new Date( + this.toLocaleString("en-US", { + timeZone: timezone, + }) + ).getTime() ); + return this; }, isInPast: function (this: Date) { const today = new Date(); today.setHours(0, 0, 0, 0); return this < today; }, + set: function (this: Date, opts: DateSetOptions) { + if (opts.timezone) return this.setTimezone(opts.timezone).set({ ...opts, timezone: undefined }); + if (opts.time != null) this.setTime(opts.time); + if (opts.utc != null) { + if (opts.year != null) this.setUTCFullYear(opts.year); + if (opts.month != null) this.setUTCMonth(opts.month); + if (opts.date != null) this.setUTCDate(opts.date); + if (opts.hours != null) this.setUTCHours(opts.hours); + if (opts.minutes != null) this.setUTCMinutes(opts.minutes); + if (opts.seconds != null) this.setUTCSeconds(opts.seconds); + if (opts.milliseconds != null) this.setUTCMilliseconds(opts.milliseconds); + } else { + if (opts.year != null) this.setFullYear(opts.year); + if (opts.month != null) this.setMonth(opts.month); + if (opts.date != null) this.setDate(opts.date); + if (opts.hours != null) this.setHours(opts.hours); + if (opts.minutes != null) this.setMinutes(opts.minutes); + if (opts.seconds != null) this.setSeconds(opts.seconds); + if (opts.milliseconds != null) this.setMilliseconds(opts.milliseconds); + } + return this; + }, + add: function (this: Date, opts: DateSetOptions) { + if (opts.timezone) return this.setTimezone(opts.timezone).set({ ...opts, timezone: undefined }); + if (opts.utc) delete opts.utc; + if (opts.time != null) opts.time += this.getTime(); + if (opts.year != null) opts.year += this.getFullYear(); + if (opts.month != null) opts.month += this.getMonth(); + if (opts.date != null) opts.date += this.getDate(); + if (opts.hours != null) opts.hours += this.getHours(); + if (opts.minutes != null) opts.minutes += this.getMinutes(); + if (opts.seconds != null) opts.seconds += this.getSeconds(); + if (opts.milliseconds != null) opts.milliseconds += this.getMilliseconds(); + + return this.set(opts); + }, addYear: function (this: Date, years: number, month: number = 0, date: number = 0) { return this.setFullYear(this.getFullYear() + years, this.getMonth() + month, this.getDate() + date); }, @@ -61,9 +113,6 @@ declare global { */ nowSeconds(): number; } -} - -declare global { interface Date { /** * specifies the timezone for the current date @@ -85,51 +134,115 @@ declare global { * Add a number of years to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addYear(1) + * new Date().addYear(1) // e.g. returns: 1640252854242 */ addYear(years: number, month?: number, date?: number): number; /** * Add a number of months to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addMonth(1) + * new Date().addMonth(1) // e.g. returns: 1640252854242 */ addMonth(months: number, date?: number): number; /** * Add a number of days to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addDate(1) + * new Date().addDate(1) // e.g. returns: 1640252854242 */ addDate(days: number): number; /** * Add a number of hours to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addHours(1) + * new Date().addHours(1) // e.g. returns: 1640252854242 */ addHours(hours: number, minutes?: number, seconds?: number, milliseconds?: number): number; /** * Add a number of minutes to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addMinutes(1) + * new Date().addMinutes(1) // e.g. returns: 1640252854242 */ addMinutes(minutes: number, seconds?: number, milliseconds?: number): number; /** * Add a number of seconds to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addSeconds(1) + * new Date().addSeconds(1) // e.g. returns: 1640252854242 */ addSeconds(seconds: number, milliseconds?: number): number; /** * Add a number of milliseconds to the current date * @returns {number} timestamp in milliseconds * @example - * new Date().addMilliseconds(1) + * new Date().addMilliseconds(1) // e.g. returns: 1640252854242 */ addMilliseconds(milliseconds: number): number; + /** + * Sets the date and time value and returns the Date object + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + * @example + * new Date().set({ time: 0 }) // sets the date to 1970-01-01 00:00:00.000 UTC and returns the date object + * new Date().set({ year: 2020 }) // sets the year to 2020 and returns the date object + * new Date().set({ month: 1 }) // sets the month to february and returns the date object + * new Date().set({ date: 20 }) // sets the current date of the month to 20 and returns the date object + * new Date().set({ hours: 13 }) // sets the current hour to 1pm (13 o'clock) and returns the date object + * new Date().set({ minutes: 59 }) // sets the current minute to 59 and returns the date object + * new Date().set({ seconds: 30 }) // sets the current second to 30 and returns the date object + * new Date().set({ milliseconds: 825 }) // sets the current millisecond to 825 (.825s) and returns the date object + * + * // sets the date to 1970-01-01 12:30:10.500 local time and returns the date object + * new Date().set({ time: 0, hours: 12, minutes: 30, seconds:10, milliseconds: 500 }) + * + * // by specifying the utc option, the options (year, month, date, hours, minutes, seconds, milliseconds) will be set in UTC time + * new Date().set({ utc: true, hour: 2 }) // sets the current hour to 2am (2 o'clock) UTC (not local time!) and returns the date object + * + * new Date().set({ timezone: "GMT" }) // sets the current timezone to GMT and returns the date object + */ + set(opts: { + time?: number; + year?: number; + month?: number; + date?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + utc?: boolean; + timezone?: string; + }): Date; + /** + * Adds the specified object to the current date and returns the Date object + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + * @example + * new Date().add({ time: 0 }) // adds 0 milliseconds to the current date and returns the date object + * new Date().add({ hours: 12 }) // adds 12 hours to the current date and returns the date object + * new Date().add({ year: 1 }) // adds 1 year to the current date and returns the date object + * new Date().add({ month: 1 }) // adds 1 month to the current date and returns the date object + * new Date().add({ date: 20 }) // adds 20 days to the current date and returns the date object + * new Date().add({ hours: 13 }) // adds 13 hours to the current date and returns the date object + * new Date().add({ minutes: 59 }) // adds 59 minutes to the current date and returns the date object + * new Date().add({ seconds: 30 }) // adds 30 seconds to the current date and returns the date object + * new Date().add({ milliseconds: 825 }) // adds 825 milliseconds to the current date and returns the date object + * + * // adds 1 year, 1 month, 1 day, 1 hour, 1 minute, 1 second and 1 millisecond to the current date and returns the date object + * new Date().add({ year: 1, month: 1, date: 1, hours: 1, minutes: 1, seconds: 1, milliseconds: 1 }) + * + * new Date().add({ timezone: "GMT", hours: 1 }) // sets the current timezone to GMT, adds 1 hour and returns the date object + * + */ + add(opts: { + time?: number; + year?: number; + month?: number; + date?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + timezone?: string; + }): Date; } } diff --git a/src/Global.ts b/src/Global.ts index 1ebfd25..00a0302 100644 --- a/src/Global.ts +++ b/src/Global.ts @@ -7,6 +7,7 @@ try { } if (!globalThis.setIntervalNow) { globalThis.setIntervalNow = function (callback: Function, milliseconds?: number, ...args: any[]) { + if (typeof callback !== "function") return const func = callback.bind(this, ...args); func(); return setInterval(func, milliseconds); diff --git a/src/Object.ts b/src/Object.ts deleted file mode 100644 index c77ac02..0000000 --- a/src/Object.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { define } from "./Util"; - -define(Object.prototype, { - forEach: function (callback: (element: any, index?: string) => any) { - // @ts-ignore - return Object.keys(this).forEach((key) => callback(this[key], key)); - }, - map: function (callback: (element: any, index?: string) => any) { - const obj = {}; - - Object.keys(this).forEach((key) => { - // @ts-expect-error - obj[key] = callback(this[key], key); - }); - return obj; - }, - keys: function (): any[] { - return Object.keys(this); - }, - entries: function (): any[] { - return Object.entries(this); - }, - merge: function (obj: any) { - // this will overwrite if obj has the same property - return mergeDeep(obj || {}, this); - }, - stringify: function () { - return JSON.stringify(this); - }, -}); - -function mergeDeep(target: any, ...sources: any): any { - if (!sources.length) return target; - const source = sources.shift(); - - if (isObject(target) && isObject(source)) { - for (const key in source) { - if (isObject(source[key])) { - if (!target[key]) Object.assign(target, { [key]: {} }); - mergeDeep(target[key], source[key]); - } else { - Object.assign(target, { [key]: source[key] }); - } - } - } - - return mergeDeep(target, ...sources); -} - -function isObject(item: any) { - return item && typeof item === "object" && !Array.isArray(item) && item?.constructor?.name === "Object"; -} - -declare global { - interface Object { - /** - * Performs the specified action for each element in an array. - * @param {} callback function that accepts the following arguments: - * - value - * - key - * @example - * {a: 1, b: 2, c: 3}.forEach((v,k)=>console.log(`${k}: ${v}`)); - * // a: 1 - * // b: 2 - * // c: 3 - */ - forEach(callback: (element: any, index?: string) => any): void; - /** - * Calls a defined callback function on each element of an object, and returns an object that contains the results. - * @param {} callback function that accepts the following arguments: - * - value - * - key - * @example - * {a: 1, b: 2, c: 3}.map((v,k) => v*25); // {a: 25, b: 50, c: 75} - */ - map(callback: (element: any, index?: string) => any): this; - /** - * Returns an array consisting of the keys of the object - * @returns {string[]} array containing the keys of the object - * @example - * {a: 1, b: 2, c: 3}.keys() // ["a", "b", "c"] - */ - keys(): string[]; - /** - * Returns an array consisting of the key value pairs of the object - * @returns {string[]} array containing the key value paris of the object - * @example - * {a: 1, b: 2, c: 3}.entries() // [["a", 1], ["b", 2], ["c", 3]] - */ - entries(): Array<[string, any]>; - /** - * Merge the original object with the given object. - * Keys will be overwritten if they occure in both objects, the last occurrence will be kept in the resulting object - * @param {object} obj - * @returns {any} - * @example - * {a: 1, b: 2, c: 3}.merge({d: 4, e: 5, f: 6}) // {a:1, b:2, c: 3, d: 4, e: 5, f: 6} - * {a: 1, b: 2, c: 3}.merge({a: 4}) // {a:4, b:2, c: 3} - */ - merge(obj: any): any; - /** - * Convert the object to its string representation, uses JSON.stringify under the hood - * @returns {string} - * @example - * {a: 1, b: 2, c: 3}.stringify() // "{\"a\":1, \"b\":2, \"c\":3}" - */ - stringify(): string; - } - - interface ObjectConstructor {} -} -export {}; diff --git a/src/Promise.ts b/src/Promise.ts index 7576fd1..6f8c4c0 100644 --- a/src/Promise.ts +++ b/src/Promise.ts @@ -17,7 +17,7 @@ declare global { * rej("Promised rejected, but caught in console.error"); *}).caught(); // will not throw the promise, but log the error in the console */ - caught(): this; + caught?(): this; } } diff --git a/src/index.ts b/src/index.ts index 81994e7..4584a2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,6 @@ import "./Array"; import "./Global"; import "./Math"; import "./Number"; -import "./Object"; import "./Promise"; import "./String"; import "./Date"; @@ -11,7 +10,6 @@ export * from "./Array"; export * from "./Global"; export * from "./Math"; export * from "./Number"; -export * from "./Object"; export * from "./Promise"; export * from "./String"; export * from "./Date"; pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy