-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEssentialJS.js
More file actions
402 lines (384 loc) · 12.4 KB
/
EssentialJS.js
File metadata and controls
402 lines (384 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*===================NOTE===================*/
/*This script was made by Himanshu Sultaina */
/* Please don't claim this as your own work */
/* This script is under MIT License */
/*==========================================*/
"use strict";
//These are the functions for Math
/*
* returns a rounded version of the number PI
* @param {Number} num - The number that PI will be rounded to
* @returns {Number} - The rounded PI
*/
Math.PI2 = (till) => {
// Value of PI till the first 100 digits
const PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067;
// Use of ?? makes sure that till is not undefined
return Number(PI.toFixed(till ?? 2));
};
Math.randomFloat = (max, min = 0) => Math.random() * (max - min + 1) + min;
Math.randomNum = (max, min = 0) => Math.floor(Math.random() * (max - min + 1)) + min;
Math.randomcolor = () => `rgb(${Math.randomNum(255)},${Math.randomNum(255)},${Math.randomNum(255)})`;
/*
* This function compares wheter a number falls in a certain range
* @param {number} num - The number to be checked
* @param {number} min - The minimum value of the range
* @param {number} max - The maximum value of the range
* @param {boolean} inclusive - Whether the range is inclusive or not
* @returns {boolean} - Returns true if the number falls in the range
*/
Math.range = (number, min, max, inclusive = false) => {
return inclusive ? number > min && number < max : number >= min && number <= max;
};
/*
* A simpler method of for loop
* @param {Function} callback - The function that will be called for each iteration
* @param {argument} args - The extra arguments that will be passed to the callback function
* @returns {undefined}
* @example
* (5).times((index, str) => {console.log(str, index)}, "Hello World!");
* > Hello World! 0
* > Hello World! 1
* > Hello World! 2
* > Hello World! 3
* > Hello World! 4
*/
Number.prototype.times = function (callback, ...args) {
for (let i = 0; i < this; i++) callback(i, ...args);
};
//These are the functions for Date
/*
* A simple function for formating string with a date
* @param {string} format - The format of the date
* @returns {string} - The formatted date
*/
Date.prototype.preset = function (preset) {
const t = (e) => ("0" + e).slice(-2);
return preset
.replace(/MMMM/g, this.getFullMonth())
.replace(/MMM/g, this.getFullMonth().slice(0, 3))
.replace(/MM/g, t(this.getMonth() + 1))
.replace(/YYYY/g, this.getFullYear())
.replace(/DD/g, t(this.getDate()))
.replace(/hh/g, t(this.getHours()))
.replace(/mm/g, t(this.getMinutes()))
.replace(/ss/g, t(this.getSeconds()));
};
/*
* Returns the month name
* returns {string} - The name of the month
*/
Date.prototype.getFullMonth = function () {
return ["Janurary", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][this.getMonth()];
};
/*
* Returns an array of the number of days in each month
* @returns {array} - An array of the number of days in each month
*/
Date.prototype.getMonthArray = function () {
return [31, this.getFullYear() % 4 == 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 31, 30, 31, 30];
};
//These are the functions for Arrays
/*
* Returns a random element from the array
* @returns {any} - The random element from the array
*/
Array.prototype.random = function random() {
return this[Math.randomNum(this.length - 1)];
};
/*
* checks wheter the Array is empty or not
* @returns {boolean} - Returns true if the array is empty
*/
Array.prototype.isEmpty = function empty() {
return JSON.stringify([]) == JSON.stringify(this);
};
/*
* Tries to parse all the strings to numbers
* @returns {array} - The parsed array
*/
Array.prototype.toNum = function number() {
return this.map((r) => (isNaN(r) || isNaN(parseFloat(r)) ? r : parseFloat(r)));
};
/*
* This function chunks an array into smaller arrays
* @param {number} chunkSize - The size of the chunk
* @returns {array} - The chunked array
*/
Array.prototype.chunk = function chunking(chunkSize) {
if (isNaN(Number(chunkSize))) throw new Error("chunkSize must be a number");
chunkSize = Number(chunkSize);
let chunks = [];
for (let i = 0; i <= this.length - 1; i += chunkSize) {
chunks.push(this.slice(i, i + chunkSize));
}
return chunks;
};
/*
* This function randomizes the order of an array
* @returns {array} - The randomized array
*/
Array.prototype.randomize = function randomize() {
let currentIndex = this.length,
randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[this[currentIndex], this[randomIndex]] = [this[randomIndex], this[currentIndex]];
}
return this;
};
/*
* This function filters all the duplicate elements in an array
* @returns {array} - The filtered array
*/
Array.prototype.nodupes = function nodupes() {
return this.filter((element, index, array) => array.indexOf(element) == index);
};
/*
* returns the first element of an array
* @returns {any} - The first element of the array
*/
Array.prototype.first = function first() {
return this[0];
};
/*
* returns the last element of an array
* @returns {any} - The last element of the array
*/
Array.prototype.last = function last() {
return this[this.length - 1];
};
/*
* Rotates the array right side
* @param {number} times - The amount by which the array will be rotated
* @returns {array} - The rotated array
*/
Array.prototype.rotate = function (times) {
let arr = [...this];
(times ?? 1).times(() => arr.unshift(arr.pop()));
return arr;
};
/*
* Inserts an element at the specified index
* @param {any} element - The element to be inserted
* @param {number} index - The index at which the element will be inserted
* @returns {array} - The array with the element inserted
*/
Array.prototype.insert = function (index, element) {
if (isNaN(Number(index))) throw new Error("Index must be a number");
index = Number(index);
if (index < 0 || index >= this.length) throw new Error("Index out of bounds");
this.splice(index, 0, element);
return this;
};
/*
* Removes a perticular element from the array
* @param {any} element - The element to be removed
* @returns {array} - The array with the element removed
*/
Array.prototype.remove = function (element) {
let index = this.indexOf(element);
if (index == -1) return this;
this.splice(index, 1);
return this;
};
/*
* Removes all instances of the element from the array
* @param {any} element - The element to be removed
* @returns {array} - The array with the element removed
*/
Array.prototype.removeAll = function (element) {
var i = 0;
while (i < this.length) {
if (this[i] === element) {
this.splice(i, 1);
} else {
i++;
}
}
return this;
};
//Functions related to Objects
Object.isEmpty = (obj) => JSON.stringify({}) === JSON.stringify(obj);
//Functions related to Strings
/*
* Capitalizes the first letter of all the words in a string
* @returns {string} - The converted string
*/
String.prototype.title = function title() {
return this.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase());
};
/*
* Checks whetert he given string is a valid url or not
* @param {number} [method=0] - Each method uses a different way of checking wheter the string is a valid url or not. Chose as per you liking
* @returns {boolean} - Returns true if the string is a valid url
*/
String.prototype.isURL = function isURL(method = 1) {
if (isNaN(Number(method))) throw new Error("method must be a number");
method = Number(method);
if (method <= 0 || method > 5) throw new RangeError("Invalid method Number. Please use methods between 1 to 5");
if (method === 1) {
try {
return Boolean(new URL(urlString));
} catch (e) {
return false;
}
} else if (method === 2) {
var a = document.createElement("a");
a.href = str;
return a.host && a.host != window.location.host;
} else if (method === 3) {
var inputElement = document.createElement("input");
inputElement.type = "url";
inputElement.value = urlString;
if (!inputElement.checkValidity()) {
return false;
} else {
return true;
}
} else if (method === 4) {
return !!/(?:https?):\/\/(\w+:?\w*)?(\S+)(:\d+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/.test(urlString);
} else if (method === 5) {
return string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g) !== null;
} else {
throw new RangeError("Invalid method Number. Please use methods between 1 to 5");
}
};
//Functions related to Elements
/*
* Sets tooltip to the element or returns the tooltip of the element
* @param {string} text - The text to be displayed in the tooltip
*/
Node.prototype.tooltip = function tooltip(text) {
return this.attr("title", text);
};
/*
* Sets/Returns the attribute of the element
* @param {string} attr - The attribute to be set/returned
* @param {string} [value] - The value to be set to the attribute
*/
Node.prototype.attr = function attr(attr, value) {
if (value === void 0) {
return this.getAttribute(attr);
} else {
return this.setAttribute(attr, value);
}
};
/*
* Converts NodeList into array
*/
NodeList.prototype.array = function array() {
return [...this];
};
/*
* Converts a string to an element node
* @param {string} str - The string to be converted
* @returns {element} - The parsed element
*/
const createElm = (html) => {
const t = document.createElement("div");
t.innerHTML = html;
return t.removeChild(t.firstElementChild);
};
//All the cursour Information is stored here
`
let cursourInfo = { mouseonpage: false, CursorX: 0, CursorY: 0, clicking: false };
if (window.Event) document.captureEvents(Event.MOUSEMOVE);
document.onmouseenter = function () {
cursourInfo.mouseonpage = true;
};
document.onmouseleave = function () {
cursourInfo.mouseonpage = false;
};
document.onmousedown = function () {
cursourInfo.clicking = true;
};
document.onmouseup = function () {
cursourInfo.clicking = false;
};
document.onmousemove = (e) => {
cursourInfo.CursorX = window.Event ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
cursourInfo.CursorY = window.Event ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
};`;
const sum = (arr) => {
return arr.reduce((a, b) => a + b, 0);
};
class Device {
isPhone() {
return ["Android", "webOS", "iPhone", "iPad", "BlackBerry", "Windows Phone"].some((a) => navigator.userAgent.includes(a));
}
OS() {
let i = (i) => navigator.userAgent.match(i);
if (i("Win")) return "Windows";
else if (i("Mac")) return "Macintosh";
else if (i("Linux")) return "Linux";
else if (i("Android")) return "Android";
else if (i("like Mac")) return "iOS";
return "Unknown";
}
timezone() {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
}
class Page {
find_parameter(parameter) {
let href = window.location.href;
let regex = new RegExp(`[&?]${parameter}=([^&]*)`, "i");
let match = href.match(regex);
return match[1];
}
cookie_dict() {
let cookie_dict = {};
let cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].split("=");
cookie_dict[cookie[0].trim()] = cookie[1];
}
return cookie_dict;
}
in_iframe() {
return window.location != window.parent.location;
}
async is_online(fetch_check = false) {
if (!fetch_check) {
return navigator.onLine;
} else {
return await fetch("https://i.imgur.com/8pNz0UC.png", { cache: "no-store" })
.then((r) => r.blob())
.then((r) => true)
.catch((error) => false);
}
}
}
// Instesting functions that I am planning on adding
const Dummy_class = class Dummy {
static isinstance(variable, type_variable) {
return type(variable) == type_variable;
}
static rgb(r, g, b) {
return `rgb(${r},${g}${b}`;
}
static isfunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === "[object Function]";
}
static rand_bool() {
return Math.randomNum(100) % 2 == 0;
}
find_from_array(string, match_array) {
for (var i = 0; match_array.length >= i; i++) {
if (string.includes(match_array[i])) return { found: true, from: match_array[i] };
}
return { found: false };
}
InsertCss(css) {
let t = document.createElement("style");
return t.appendChild(document.createTextNode(css)), document.head.appendChild(t), t;
}
geolocation() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition((o) => {
(Dummy.lat = o.coords.latitude), (Dummy.lon = o.coords.longitude);
});
}
};