/**
* @file
* 'Nother Opensource Yucky Project? Impossible!
* Functions that almost no one needs.
* @version 0.0.1
* @license The MIT License (MIT)
* @author Noypi <noypi@alwaysdata.net>
* @copyright Copyright (c) 2023 Noypi <noypi@alwaysdata.net>
*/
/**
* Core NOYPI namespace
*
* @namespace
*/
noypiJS = {
/**
* NOYPI arr funcs
* @namespace
* @memberOf noypiJS
*/
arr :{
/**
* Chunks an array into arrays with a specified number of elements.
*
* @param {Array} array - The array to work on.
* @param {number} length - The size of each chunk.
* @param {boolean} [preserveKeys=false] - Optional. When set to true, keys will be preserved.
* Default is false, which will reindex the chunks numerically.
* @returns {Array} A multidimensional numerically indexed array, starting with zero,
* with each dimension containing length elements.
* @throws {Error} If length is less than 1, an error will be thrown.
*/
array_chunk: function(array, length, preserveKeys = false) {
if (length < 1) {
throw new Error('Length must be greater than or equal to 1.');
}
const result = [];
let chunk = [];
let index = 0;
for (const key in array) {
if (array.hasOwnProperty(key)) {
if (preserveKeys) {
chunk[key] = array[key];
} else {
chunk.push(array[key]);
}
index++;
if (index >= length) {
result.push(chunk);
chunk = [];
index = 0;
}
}
}
if (chunk.length > 0) {
result.push(chunk);
}
return result;
},
/**
* Returns the values from a single column in the input array.
*
* @param {Array} array - A multi-dimensional array or an array of objects from which to pull a column of values from.
* If an array of objects is provided, then public properties can be directly pulled.
* In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods.
* @param {number|string|null} column_key - The column of values to return. This value may be an integer key of the column
* you wish to retrieve, or it may be a string key name for an associative array or property name.
* It may also be null to return complete arrays or objects (this is useful together with index_key to reindex the array).
* @param {number|string|null} [index_key=null] - The column to use as the index/keys for the returned array.
* This value may be the integer key of the column, or it may be the string key name.
* The value is cast as usual for array keys (however, prior to PHP 8.0.0, objects supporting conversion to string were also allowed).
* @returns {Array} An array of values representing a single column from the input array.
*/
array_column: function(array, column_key, index_key = null) {
const result = [];
for (const item of array) {
if (typeof item === 'object') {
if (column_key === null) {
result.push(item);
} else if (column_key in item) {
if (index_key === null) {
result.push(item[column_key]);
} else if (index_key in item) {
result[item[index_key]] = item[column_key];
}
}
}
}
return result;
},/**
* Creates an array by using the values from the keys array as keys
* and the values from the values array as the corresponding values.
*
* @param {Array} keys - Array of keys to be used. Illegal values for key will be converted to string.
* @param {Array} values - Array of values to be used.
* @returns {Object} The combined object (associative array).
* @throws {Error} If the number of elements in keys and values does not match.
*/
array_combine: function(keys, values) {
if (keys.length !== values.length) {
throw new Error('Number of elements in keys and values must match.');
}
const result = {};
for (let i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
return result;
},
// array_map — Applies the callback to the elements of the given arrays
/**
* Applies the callback to the elements of the given arrays.
*
* @param {Function} callback - The callback function to apply to each element.
* @param {...Array} arrays - One or more arrays to apply the callback to.
* @returns {Array} An array containing the results of applying the callback to each element.
*/
array_map: function(callback, ...arrays) {
const result = [];
const length = Math.max(...arrays.map(arr => arr.length));
for (let i = 0; i < length; i++) {
const args = arrays.map(arr => arr[i]);
result.push(callback(...args));
}
return result;
},
// array_merge_recursive — Merge one or more arrays recursively
/**
* Merge one or more arrays recursively.
*
* @param {...Object} arrays - One or more arrays to merge recursively.
* @returns {Object} A merged object with recursive merging of arrays.
*/
array_merge_recursive: function(...arrays) {
function mergeRecursive(dest, src) {
for (const key in src) {
if (src.hasOwnProperty(key)) {
if (src[key] instanceof Object && dest[key] instanceof Object) {
dest[key] = mergeRecursive(dest[key], src[key]);
} else {
dest[key] = src[key];
}
}
}
return dest;
}
const result = {};
for (const array of arrays) {
mergeRecursive(result, array);
}
return result;
},
// array_merge — Merge one or more arrays
/**
* Merge one or more arrays.
*
* @param {...Array} arrays - One or more arrays to merge.
* @returns {Array} A merged array.
*/
array_merge: function(...arrays) {
return [].concat(...arrays);
},
// array_multisort — Sort multiple or multi-dimensional arrays
/**
* Sort multiple or multi-dimensional arrays.
*
* @param {...Array} arrays - One or more arrays to sort.
*/
array_multisort: function(...arrays) {
for (let i = 0; i < arrays.length - 1; i++) {
for (let j = 0; j < arrays[i].length; j++) {
for (let k = i + 1; k < arrays.length; k++) {
if (typeof arrays[k][j] !== 'undefined') {
if (arrays[i][j] > arrays[k][j]) {
for (const array of arrays) {
const temp = array[i][j];
array[i][j] = array[k][j];
array[k][j] = temp;
}
}
break;
}
}
}
}
},
// array_pad — Pad array to the specified length with a value
/**
* Pad an array to the specified length with a value.
*
* @param {Array} array - The array to pad.
* @param {number} size - The new size of the array.
* @param {*} value - The value to pad the array with.
* @returns {Array} A new array padded to the specified length with the given value.
*/
array_pad: function(array, size, value) {
if (size <= array.length) {
return array.slice(0, size);
}
const result = [...array];
while (result.length < size) {
result.push(value);
}
return result;
},
// array_pop — Pop the element off the end of array
/**
* Pop the element off the end of an array.
*
* @param {Array} array - The array to pop from.
* @returns {*} The removed element.
*/
array_pop: function(array) {
return array.pop();
},
// array_product — Calculate the product of values in an array
/**
* Calculate the product of values in an array.
*
* @param {Array} array - The array to calculate the product from.
* @returns {number} The product of the array values.
*/
array_product: function(array) {
return array.reduce((product, value) => product * value, 1);
},
/**
* Push one or more elements onto the end of an array.
*
* @param {Array} array - The array to push elements onto.
* @param {...*} elements - One or more elements to push onto the array.
* @returns {number} The new length of the array.
*/
array_push: function(array, ...elements) {
return array.push(...elements);
},
// array_rand — Pick one or more random keys out of an array
array_rand: function(array, num = 1) {
/**
* Pick one or more random keys out of an array.
*
* @param {Array} array - The array to pick random keys from.
* @param {number} num - Optional. The number of random keys to pick.
* @returns {*} A random key (or an array of random keys if num > 1).
*/
const keys = Object.keys(array);
if (num === 1) {
return keys[Math.floor(Math.random() * keys.length)];
} else {
const result = [];
for (let i = 0; i < num; i++) {
const randomKey = keys[Math.floor(Math.random() * keys.length)];
result.push(randomKey);
}
return result;
}
},
// array_reduce — Iteratively reduce the array to a single value using a callback function
/**
* Iteratively reduce the array to a single value using a callback function.
*
* @param {Array} array - The array to reduce.
* @param {Function} callback - A callback function to apply to each element in the array.
* @param {*} [initialValue=null] - Optional. The initial value to start the reduction with.
* @returns {*} The reduced value.
*/
array_reduce: function(array, callback, initialValue = null) {
let accumulator = initialValue;
for (const element of array) {
accumulator = callback(accumulator, element);
}
return accumulator;
},// array_replace — Replaces elements from passed arrays into the first array
array_replace: function(...arrays) {
/**
* Replaces elements from passed arrays into the first array.
*
* @param {...Object} arrays - Arrays to merge into the first array.
* @returns {Object} The merged object with replaced elements.
*/
const result = {};
for (const array of arrays) {
for (const key in array) {
if (array.hasOwnProperty(key)) {
result[key] = array[key];
}
}
}
return result;
},
// array_reverse — Return an array with elements in reverse order
array_reverse: function(array, preserveKeys = false) {
/**
* Return an array with elements in reverse order.
*
* @param {Array} array - The array to reverse.
* @param {boolean} [preserveKeys=false] - Optional. If true, preserve original keys.
* @returns {Array} The reversed array.
*/
const result = [];
if (preserveKeys) {
const keys = Object.keys(array).reverse();
for (const key of keys) {
result[key] = array[key];
}
} else {
for (let i = array.length - 1; i >= 0; i--) {
result.push(array[i]);
}
}
return result;
},
// array_search — Searches the array for a given value and returns the first corresponding key if successful
array_search: function(needle, haystack, strict = false) {
/**
* Searches the array for a given value and returns the first corresponding key if successful.
*
* @param {*} needle - The value to search for.
* @param {Array|Object} haystack - The array to search in.
* @param {boolean} [strict=false] - Optional. If true, use strict comparison (===).
* @returns {string|int|boolean} The first key where the value was found, or false if not found.
*/
for (const key in haystack) {
if (haystack.hasOwnProperty(key)) {
if (strict ? haystack[key] === needle : haystack[key] == needle) {
return key;
}
}
}
return false;
},
// array_shift — Shift an element off the beginning of array
array_shift: function(array) {
/**
* Shift an element off the beginning of an array.
*
* @param {Array} array - The array to shift from.
* @returns {*} The shifted element.
*/
return array.shift();
},
// array_slice — Extract a slice of the array
array_slice: function(array, offset, length = null, preserveKeys = false) {
/**
* Extract a slice of the array.
*
* @param {Array} array - The array to slice.
* @param {number} offset - The start index.
* @param {number|null} [length=null] - Optional. The length of the slice.
* @param {boolean} [preserveKeys=false] - Optional. If true, preserve original keys.
* @returns {Array} The sliced array.
*/
if (preserveKeys) {
const keys = Object.keys(array).slice(offset, length !== null ? offset + length : undefined);
const result = {};
for (const key of keys) {
result[key] = array[key];
}
return result;
} else {
return array.slice(offset, length);
}
},
// array_splice — Remove a portion of the array and replace it with something else
array_splice: function(array, start, length = null, replacement = []) {
/**
* Remove a portion of the array and replace it with something else.
*
* @param {Array} array - The array to splice.
* @param {number} start - The starting index.
* @param {number|null} [length=null] - Optional. The number of elements to remove.
* @param {Array} [replacement=[]] - Optional. The elements to insert as replacement.
* @returns {Array} An array containing the removed elements.
*/
return array.splice(start, length, ...replacement);
},
// array_sum — Calculate the sum of values in an array
array_sum: function(array) {
/**
* Calculate the sum of values in an array.
*
* @param {Array} array - The array to calculate the sum from.
* @returns {number} The sum of the array values.
*/
return array.reduce((sum, value) => sum + value, 0);
},
// array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
array_udiff_assoc: function(array1, array2, compareFunc) {
/**
* Computes the difference of arrays with additional index check, compares data by a callback function.
*
* @param {Array|Object} array1 - The first array to compare.
* @param {Array|Object} array2 - The second array to compare.
* @param {Function} compareFunc - A callback function for data comparison.
* @returns {Array} An array containing the values from array1 that are not present in array2, based on the callback function.
*/
const result = [];
for (const key in array1) {
if (array1.hasOwnProperty(key)) {
const value1 = array1[key];
const value2 = array2[key];
if (compareFunc(value1, value2) !== 0) {
result[key] = value1;
}
}
}
return result;
},
// array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by callback functions
array_udiff_uassoc: function(array1, array2, dataCompareFunc, indexCompareFunc) {
/**
* Computes the difference of arrays with additional index check, compares data and indexes by callback functions.
*
* @param {Array|Object} array1 - The first array to compare.
* @param {Array|Object} array2 - The second array to compare.
* @param {Function} dataCompareFunc - A callback function for data comparison.
* @param {Function} indexCompareFunc - A callback function for index comparison.
* @returns {Array} An array containing the values from array1 that are not present in array2, based on the callback functions.
*/
const result = {};
for (const key in array1) {
if (array1.hasOwnProperty(key)) {
const value1 = array1[key];
const value2 = array2[key];
if (dataCompareFunc(value1, value2) !== 0 || indexCompareFunc(key, key) !== 0) {
result[key] = value1;
}
}
}
return result;
},
// array_udiff — Computes the difference of arrays by using a callback function for data comparison
array_udiff: function(array1, array2, compareFunc) {
/**
* Computes the difference of arrays by using a callback function for data comparison.
*
* @param {Array|Object} array1 - The first array to compare.
* @param {Array|Object} array2 - The second array to compare.
* @param {Function} compareFunc - A callback function for data comparison.
* @returns {Array} An array containing the values from array1 that are not present in array2, based on the callback function.
*/
const result = [];
for (const key in array1) {
if (array1.hasOwnProperty(key)) {
const value1 = array1[key];
const value2 = array2[key];
if (compareFunc(value1, value2) !== 0) {
result[key] = value1;
}
}
}
return result;
},
// array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
array_uintersect_assoc: function(array1, array2, compareFunc) {
/**
* Computes the intersection of arrays with additional index check, compares data by a callback function.
*
* @param {Array|Object} array1 - The first array to compare.
* @param {Array|Object} array2 - The second array to compare.
* @param {Function} compareFunc - A callback function for data comparison.
* @returns {Array} An array containing the values that are present in both array1 and array2, based on the callback function.
*/
const result = [];
for (const key in array1) {
if (array1.hasOwnProperty(key) && key in array2) {
const value1 = array1[key];
const value2 = array2[key];
if (compareFunc(value1, value2) === 0) {
result[key] = value1;
}
}
}
return result;
},
// array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
array_uintersect_uassoc: function(array1, array2, dataCompareFunc, indexCompareFunc) {
/**
* Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions.
*
* @param {Array|Object} array1 - The first array to compare.
* @param {Array|Object} array2 - The second array to compare.
* @param {Function} dataCompareFunc - A callback function for data comparison.
* @param {Function} indexCompareFunc - A callback function for index comparison.
* @returns {Array} An array containing the values that are present in both array1 and array2, based on the callback functions.
*/
const result = {};
for (const key in array1) {
if (array1.hasOwnProperty(key) && key in array2) {
const value1 = array1[key];
const value2 = array2[key];
if (dataCompareFunc(value1, value2) === 0 && indexCompareFunc(key, key) === 0) {
result[key] = value1;
}
}
}
return result;
},
// array_uintersect — Computes the intersection of arrays, compares data by a callback function
array_uintersect: function(array1, array2, compareFunc) {
/**
* Computes the intersection of arrays, compares data by a callback function.
*
* @param {Array|Object} array1 - The first array to compare.
* @param {Array|Object} array2 - The second array to compare.
* @param {Function} compareFunc - A callback function for data comparison.
* @returns {Array} An array containing the values that are present in both array1 and array2, based on the callback function.
*/
const result = [];
for (const key in array1) {
if (array1.hasOwnProperty(key) && key in array2) {
const value1 = array1[key];
const value2 = array2[key];
if (compareFunc(value1, value2) === 0) {
result[key] = value1;
}
}
}
return result;
},
// array_unique — Removes duplicate values from an array
array_unique: function(array) {
/**
* Removes duplicate values from an array.
*
* @param {Array} array - The array to remove duplicates from.
* @returns {Array} An array with duplicate values removed.
*/
return [...new Set(array)];
},
// array_unshift — Prepend one or more elements to the beginning of an array
array_unshift: function(array, ...elements) {
/**
* Prepend one or more elements to the beginning of an array.
*
* @param {Array} array - The array to prepend elements to.
* @param {...*} elements - One or more elements to prepend to the array.
* @returns {number} The new length of the array.
*/
return array.unshift(...elements);
},
// array_values — Return all the values of an array
array_values: function(array) {
/**
* Return all the values of an array.
*
* @param {Array|Object} array - The array to extract values from.
* @returns {Array} An array containing all the values.
*/
return Object.values(array);
},
// array_walk_recursive — Apply a user function recursively to every member of an array
array_walk_recursive: function(array, callback) {
/**
* Apply a user function recursively to every member of an array.
*
* @param {Array|Object} array - The array to apply the function to.
* @param {Function} callback - The callback function to apply.
*/
function walkRecursive(element, callback) {
if (typeof element === 'object') {
for (const key in element) {
if (element.hasOwnProperty(key)) {
walkRecursive(element[key], callback);
}
}
} else {
callback(element);
}
}
walkRecursive(array, callback);
},
// array_walk — Apply a user supplied function to every member of an array
array_walk: function(array, callback) {
/**
* Apply a user supplied function to every member of an array.
*
* @param {Array|Object} array - The array to apply the function to.
* @param {Function} callback - The callback function to apply.
*/
for (const key in array) {
if (array.hasOwnProperty(key)) {
callback(array[key], key);
}
}
},
// arsort — Sort an object in descending order and maintain index association
arsort: function(object) {
/**
* Sort an object in descending order and maintain index association.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => object[b] - object[a]);
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// asort — Sort an object in ascending order and maintain index association
asort: function(object) {
/**
* Sort an object in ascending order and maintain index association.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => object[a] - object[b]);
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// compact — Create an object containing variables and their values
compact: function(...vars) {
/**
* Create an object containing variables and their values.
*
* @param {...*} vars - Variables to include in the object.
* @returns {Object} An object containing variables and their values.
*/
const result = {};
for (const variable of vars) {
if (typeof variable !== 'undefined') {
result[variable] = variable;
}
}
return result;
},
// count — Counts all elements in an object or in a Countable object
count: function(object) {
/**
* Counts all elements in an object or in a Countable object.
*
* @param {Object|Array|string} object - The object or array to count.
* @returns {number} The number of elements in the object or array.
*/
if (typeof object === 'string') {
return object.length;
} else {
return Object.keys(object).length;
}
},
// current — Return the current element in an object
current: function(object) {
/**
* Return the current element in an object.
*
* @param {Object} object - The object to get the current element from.
* @returns {*} The current element.
*/
const keys = Object.keys(object);
return object[keys[keys.length - 1]];
},
// each — Return the current key and value pair from an object and advance the object cursor
each: function(object) {
/**
* Return the current key and value pair from an object and advance the object cursor.
*
* @param {Object} object - The object to get the key-value pair from.
* @returns {Array} An array containing the current key and value.
*/
const keys = Object.keys(object);
const currentKey = keys[keys.length - 1];
const currentValue = object[currentKey];
delete object[currentKey];
return [currentKey, currentValue];
},
// end — Set the internal pointer of an object to its last element
end: function(object) {
/**
* Set the internal pointer of an object to its last element.
*
* @param {Object} object - The object to set the internal pointer for.
* @returns {void}
*/
const keys = Object.keys(object);
const lastKey = keys[keys.length - 1];
while (current(object) !== object[lastKey]) {
next(object);
}
},
// extract — Import variables into the current symbol table from an object
extract: function(object) {
/**
* Import variables into the current symbol table from an object.
*
* @param {Object} object - The object to extract variables from.
* @returns {void}
*/
for (const key in object) {
if (object.hasOwnProperty(key)) {
this[key] = object[key];
}
}
},
// in_array — Checks if a value exists in an object
in_array: function(needle, object, strict = false) {
/**
* Checks if a value exists in an object.
*
* @param {*} needle - The value to search for.
* @param {Object|Array} object - The object or array to search in.
* @param {boolean} [strict=false] - Optional. If true, use strict comparison (===).
* @returns {boolean} True if the value exists in the object, otherwise false.
*/
for (const key in object) {
if (object.hasOwnProperty(key)) {
const value = object[key];
if (strict ? value === needle : value == needle) {
return true;
}
}
}
return false;
},
// key_exists — Alias of object_key_exists
key_exists: function(key, object) {
return this.object_key_exists(key, object);
},
// key — Fetch a key from an object
key: function(object) {
/**
* Fetch a key from an object.
*
* @param {Object} object - The object to fetch a key from.
* @returns {string|int|boolean} The current key in the object or false if there are no more keys.
*/
const keys = Object.keys(object);
return keys[keys.length - 1];
},
// krsort — Sort an object by key in descending order
krsort: function(object) {
/**
* Sort an object by key in descending order.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort().reverse();
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// ksort — Sort an object by key in ascending order
ksort: function(object) {
/**
* Sort an object by key in ascending order.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort();
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// list — Assign variables as if they were an object
list: function(...vars) {
/**
* Assign variables as if they were an object.
*
* @param {...*} vars - Variables to assign.
* @returns {Array} An array containing the assigned values.
*/
const result = [];
for (let i = 0; i < vars.length; i++) {
result[i] = vars[i];
}
return result;
},
// natcasesort — Sort an object using a case-insensitive "natural order" algorithm
natcasesort: function(object) {
/**
* Sort an object using a case-insensitive "natural order" algorithm.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// natsort — Sort an object using a "natural order" algorithm
natsort: function(object) {
/**
* Sort an object using a "natural order" algorithm.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => a.localeCompare(b));
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// next — Advance the internal pointer of an object
next: function(object) {
/**
* Advance the internal pointer of an object.
*
* @param {Object} object - The object to advance the pointer for.
* @returns {void}
*/
const keys = Object.keys(object);
const currentKey = keys[keys.length - 1];
const currentIndex = keys.indexOf(currentKey);
if (currentIndex < keys.length - 1) {
object[keys[currentIndex]] = object[keys[currentIndex + 1]];
delete object[keys[currentIndex + 1]];
}
},
// pos — Alias of current
pos: function(object) {
return this.current(object);
},
// prev — Rewind the internal object pointer
prev: function(object) {
/**
* Rewind the internal object pointer.
*
* @param {Object} object - The object to rewind the pointer for.
* @returns {void}
*/
const keys = Object.keys(object);
const currentKey = keys[keys.length - 1];
const currentIndex = keys.indexOf(currentKey);
if (currentIndex > 0) {
object[keys[currentIndex]] = object[keys[currentIndex - 1]];
delete object[keys[currentIndex - 1]];
}
},
// range — Create an array containing a range of elements
range: function(start, end, step = 1) {
/**
* Create an array containing a range of elements.
*
* @param {number} start - The starting value of the range.
* @param {number} end - The ending value of the range.
* @param {number} [step=1] - Optional. The step value for generating the range.
* @returns {Array} An array containing the range of elements.
*/
const result = [];
for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
},
// reset — Set the internal pointer of an object to its first element
reset: function(object) {
/**
* Set the internal pointer of an object to its first element.
*
* @param {Object} object - The object to set the internal pointer for.
* @returns {void}
*/
const keys = Object.keys(object);
const firstKey = keys[0];
while (current(object) !== object[firstKey]) {
prev(object);
}
},
// rsort — Sort an object in descending order
rsort: function(object) {
/**
* Sort an object in descending order.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const values = Object.values(object).sort((a, b) => b - a);
for (const key in object) {
if (object.hasOwnProperty(key)) {
sortedObject[key] = values.shift();
}
}
return sortedObject;
},
// shuffle — Shuffle an object
shuffle: function(object) {
/**
* Shuffle an object.
*
* @param {Object} object - The object to shuffle.
* @returns {Object} The shuffled object.
*/
const keys = Object.keys(object);
const shuffledKeys = [];
const shuffledObject = {};
while (keys.length > 0) {
const randomIndex = Math.floor(Math.random() * keys.length);
const randomKey = keys.splice(randomIndex, 1)[0];
shuffledKeys.push(randomKey);
}
for (const key of shuffledKeys) {
shuffledObject[key] = object[key];
}
return shuffledObject;
},
// sizeof — Alias of count
sizeof: function(object) {
return this.count(object);
},
// sort — Sort an object in ascending order
sort: function(object) {
/**
* Sort an object in ascending order.
*
* @param {Object} object - The object to sort.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const values = Object.values(object).sort((a, b) => a - b);
for (const key in object) {
if (object.hasOwnProperty(key)) {
sortedObject[key] = values.shift();
}
}
return sortedObject;
},
// uasort — Sort an object with a user-defined comparison function and maintain index association
uasort: function(object, compareFunc) {
/**
* Sort an object with a user-defined comparison function and maintain index association.
*
* @param {Object} object - The object to sort.
* @param {Function} compareFunc - A callback function for custom sorting.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => compareFunc(object[a], object[b]));
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// uksort — Sort an object by keys using a user-defined comparison function
uksort: function(object, compareFunc) {
/**
* Sort an object by keys using a user-defined comparison function.
*
* @param {Object} object - The object to sort.
* @param {Function} compareFunc - A callback function for custom key sorting.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => compareFunc(a, b));
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
},
// usort — Sort an object by values using a user-defined comparison function
usort: function(object, compareFunc) {
/**
* Sort an object by values using a user-defined comparison function.
*
* @param {Object} object - The object to sort.
* @param {Function} compareFunc - A callback function for custom value sorting.
* @returns {Object} The sorted object.
*/
const sortedObject = {};
const keys = Object.keys(object).sort((a, b) => compareFunc(object[a], object[b]));
for (const key of keys) {
sortedObject[key] = object[key];
}
return sortedObject;
}
,
/**
* Computes the difference of arrays with additional index check.
* Compares the first array against one or more arrays and returns the difference.
* Unlike array_diff(), the array keys are also used in the comparison.
*
* @param {Array} array - The array to compare from.
* @param {...Array} arrays - Arrays to compare against.
* @returns {Array} An array containing all the values from the first array that are not present in any of the other arrays.
*/
array_diff_assoc: function(array, ...arrays) {
const result = [];
for (const value of array) {
let found = false;
for (const arr of arrays) {
if (Array.isArray(arr) && arr.includes(value)) {
found = true;
break;
}
}
if (!found) {
result.push(value);
}
}
return result;
},// array_key_exists — Checks if the given key or index exists in the array
array_key_exists: function(key, array) {
/**
* Checks if the given key or index exists in the array.
*
* @param {string|int} key - The key or index to check.
* @param {Array|Object} array - The array to check.
* @returns {boolean} True if the key exists in the array, false otherwise.
*/
return key in array;
},
// array_key_first — Gets the first key of an array
array_key_first: function(array) {
/**
* Gets the first key of an array.
*
* @param {Array|Object} array - The array to get the first key from.
* @returns {string|int|null} The first key of the array, or null if the array is empty.
*/
for (const key in array) {
if (array.hasOwnProperty(key)) {
return key;
}
}
return null;
},
// array_key_last — Gets the last key of an array
array_key_last: function(array) {
/**
* Gets the last key of an array.
*
* @param {Array|Object} array - The array to get the last key from.
* @returns {string|int|null} The last key of the array, or null if the array is empty.
*/
let lastKey = null;
for (const key in array) {
if (array.hasOwnProperty(key)) {
lastKey = key;
}
}
return lastKey;
},
// array_keys — Return all the keys or a subset of the keys of an array
array_keys: function(array, searchValue, strict) {
/**
* Return all the keys or a subset of the keys of an array.
*
* @param {Array|Object} array - The array to get the keys from.
* @param {*} [searchValue] - Optional. If specified, only keys with this value are returned.
* @param {boolean} [strict=false] - Optional. If true, strict comparison is used (===).
* @returns {Array} An array of keys from the input array.
*/
const keys = [];
for (const key in array) {
if (array.hasOwnProperty(key)) {
if ((typeof searchValue === 'undefined') ||
(strict ? array[key] === searchValue : array[key] == searchValue)) {
keys.push(key);
}
}
}
return keys;
},
},
/**
* NOYPI obj funcs
* @namespace
* @memberOf noypiJS
*/
obj : {
/**
* Changes the case of all keys in an object.
*
* @param {Object} obj - The object to change the case of keys for.
* @param {number} [mode=CASE_LOWER] - Optional. Case conversion mode. Use CASE_LOWER for lowercase keys (default), CASE_UPPER for uppercase keys.
* @returns {Object} The object with keys in the desired case.
*/
object_change_key_case: function(obj, mode = CASE_LOWER) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (mode === CASE_LOWER) {
result[key.toLowerCase()] = obj[key];
} else if (mode === CASE_UPPER) {
result[key.toUpperCase()] = obj[key];
}
}
}
return result;
},
/**
* Split an object into chunks.
*
* @param {Object} obj - The object to split into chunks.
* @param {number} size - The size of each chunk.
* @returns {Array} An array of objects, each containing a chunk of the original object.
*/
object_chunk: function(obj, size) {
const chunkedObjects = [];
let currentChunk = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
currentChunk[key] = obj[key];
if (Object.keys(currentChunk).length === size) {
chunkedObjects.push(currentChunk);
currentChunk = {};
}
}
}
if (Object.keys(currentChunk).length > 0) {
chunkedObjects.push(currentChunk);
}
return chunkedObjects;
},
/**
* Return the values from a single column in the input object.
*
* @param {Object} obj - The input object.
* @param {string} columnKey - The column key to extract values from.
* @returns {Array} An array containing the values from the specified column.
*/
object_column: function(obj, columnKey) {
const columnValues = [];
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key].hasOwnProperty(columnKey)) {
columnValues.push(obj[key][columnKey]);
}
}
return columnValues;
},
/**
* Creates an object by using one object for keys and another for its values.
*
* @param {Object} keys - The object containing keys.
* @param {Object} values - The object containing values.
* @returns {Object} The resulting object with keys and their corresponding values.
*/
object_combine: function(keys, values) {
const combinedObject = {};
for (const key in keys) {
if (keys.hasOwnProperty(key) && values.hasOwnProperty(key)) {
combinedObject[keys[key]] = values[key];
}
}
return combinedObject;
},
/**
* Counts the occurrences of each distinct value in an object.
*
* @param {Object} obj - The object to count values in.
* @returns {Object} An object with distinct values as keys and their counts as values.
*/
object_count_values: function(obj) {
const valueCounts = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
valueCounts[value] = (valueCounts[value] || 0) + 1;
}
}
return valueCounts;
},
/**
* Computes the difference of objects with additional index check.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @returns {Object} An object containing values from obj1 that are not present in obj2.
*/
object_diff_assoc: function(obj1, obj2) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key)) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the difference of objects using keys for comparison.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @returns {Object} An object containing values from obj1 whose keys are absent from obj2.
*/
object_diff_key: function(obj1, obj2) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key)) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the difference of objects with additional index check which is performed by a user supplied callback function.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the index check.
* @returns {Object} An object containing values from obj1 that are not present in obj2 based on the callback function.
*/
object_diff_uassoc: function(obj1, obj2, callback) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key) && callback(key, key)) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the difference of objects using a callback function on the keys for comparison.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the key comparison.
* @returns {Object} An object containing values from obj1 whose keys are absent from obj2 based on the callback function.
*/
object_diff_ukey: function(obj1, obj2, callback) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key) && callback(key, key)) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the difference of objects.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @returns {Object} An object containing values from obj1 that are not present in obj2.
*/
object_diff: function(obj1, obj2) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key)) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Fill an object with values, specifying keys.
*
* @param {Object} keys - The object containing keys to fill.
* @param {any} value - The value to fill the object with.
* @returns {Object} The object with keys filled with the specified value.
*/
object_fill_keys: function(keys, value) {
const filledObject = {};
for (const key in keys) {
if (keys.hasOwnProperty(key)) {
filledObject[keys[key]] = value;
}
}
return filledObject;
},
/**
* Fill an object with values.
*
* @param {Object} obj - The object to fill with values.
* @param {any} value - The value to fill the object with.
* @returns {Object} The object with all keys filled with the specified value.
*/
object_fill: function(obj, value) {
const filledObject = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
filledObject[key] = value;
}
}
return filledObject;
},
/**
* Filters elements of an object using a callback function.
*
* @param {Object} obj - The object to filter.
* @param {Function} callback - The callback function to filter elements.
* @returns {Object} The filtered object.
*/
object_filter: function(obj, callback) {
const filteredObject = {};
for (const key in obj) {
if (obj.hasOwnProperty(key) && callback(obj[key])) {
filteredObject[key] = obj[key];
}
}
return filteredObject;
},
/**
* Exchanges all keys with their associated values in an object.
*
* @param {Object} obj - The object to flip keys and values.
* @returns {Object} The object with keys and values flipped.
*/
object_flip: function(obj) {
const flippedObject = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
flippedObject[obj[key]] = key;
}
}
return flippedObject;
},
/**
* Computes the intersection of objects with additional index check.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @returns {Object} An object containing values from obj1 that are present in obj2.
*/
object_intersect_assoc: function(obj1, obj2) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Computes the intersection of objects using keys for comparison.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @returns {Object} An object containing values from obj1 whose keys are present in obj2.
*/
object_intersect_key: function(obj1, obj2) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Computes the intersection of objects with additional index check, compares indexes by a callback function.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the index check.
* @returns {Object} An object containing values from obj1 that are present in obj2 based on the callback function.
*/
object_intersect_uassoc: function(obj1, obj2, callback) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key) && callback(key, key)) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Computes the intersection of objects using a callback function on the keys for comparison.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the key comparison.
* @returns {Object} An object containing values from obj1 whose keys are present in obj2 based on the callback function.
*/
object_intersect_ukey: function(obj1, obj2, callback) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key) && callback(key, key)) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Computes the intersection of objects.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @returns {Object} An object containing values from obj1 that are present in obj2.
*/
object_intersect: function(obj1, obj2) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Checks whether a given object is a list.
*
* @param {Object} obj - The object to check.
* @returns {boolean} True if the object is a list (has numerical keys starting from 0), false otherwise.
*/
object_is_list: function(obj) {
let index = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key) && key !== index.toString()) {
return false;
}
index++;
}
return true;
},
/**
* Checks if the given key or index exists in the object.
*
* @param {string|int} key - The key or index to check.
* @param {Object} obj - The object to check.
* @returns {boolean} True if the key or index exists in the object, false otherwise.
*/
object_key_exists: function(key, obj) {
return obj.hasOwnProperty(key);
},
/**
* Gets the first key of an object.
*
* @param {Object} obj - The object to get the first key from.
* @returns {string|null} The first key of the object or null if the object is empty.
*/
object_key_first: function(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return key;
}
}
return null;
},
/**
* Gets the last key of an object.
*
* @param {Object} obj - The object to get the last key from.
* @returns {string|null} The last key of the object or null if the object is empty.
*/
object_key_last: function(obj) {
let lastKey = null;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
lastKey = key;
}
}
return lastKey;
},
/**
* Return all the keys or a subset of the keys of an object.
*
* @param {Object} obj - The object to get the keys from.
* @param {string} [searchValue] - Optional. If provided, only keys with this value are returned.
* @param {boolean} [strict=false] - Optional. Whether to do a strict (===) comparison when searching for keys.
* @returns {Array} An array containing the keys of the object.
*/
object_keys: function(obj, searchValue, strict = false) {
const keys = [];
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (searchValue !== undefined) {
if (strict && obj[key] === searchValue) {
keys.push(key);
} else if (!strict && obj[key] == searchValue) {
keys.push(key);
}
} else {
keys.push(key);
}
}
}
return keys;
},
/**
* Applies the callback to the elements of the given objects.
*
* @param {Function} callback - The callback function to apply to each element.
* @param {...Object} objects - The objects to apply the callback on.
* @returns {Array} An array containing the results of applying the callback to the elements.
*/
object_map: function(callback, ...objects) {
const results = [];
for (const obj of objects) {
const resultObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
resultObj[key] = callback(obj[key]);
}
}
results.push(resultObj);
}
return results;
},
/**
* Merge one or more objects recursively.
*
* @param {...Object} objects - The objects to merge.
* @returns {Object} The merged object.
*/
object_merge_recursive: function(...objects) {
const mergedObject = {};
for (const obj of objects) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
mergedObject[key] = object_merge_recursive(mergedObject[key] || {}, obj[key]);
} else {
mergedObject[key] = obj[key];
}
}
}
}
return mergedObject;
},
/**
* Merge one or more objects.
*
* @param {...Object} objects - The objects to merge.
* @returns {Object} The merged object.
*/
object_merge: function(...objects) {
const mergedObject = {};
for (const obj of objects) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
mergedObject[key] = obj[key];
}
}
}
return mergedObject;
},
/**
* Sort multiple or multi-dimensional objects.
*
* @param {...Object} objects - The objects to sort.
*/
object_multisort: function(...objects) {
// Sort the objects using a sorting algorithm of your choice.
},
/**
* Pad object to the specified length with a value.
*
* @param {Object} obj - The object to pad.
* @param {number} size - The length to pad the object to.
* @param {any} value - The value to use for padding.
* @returns {Object} The padded object.
*/
object_pad: function(obj, size, value) {
while (Object.keys(obj).length < size) {
obj[Object.keys(obj).length] = value;
}
return obj;
},
/**
* Pop the element off the end of object.
*
* @param {Object} obj - The object to pop from.
* @returns {any} The value of the popped element.
*/
object_pop: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return undefined;
}
const lastKey = keys[keys.length - 1];
const lastValue = obj[lastKey];
delete obj[lastKey];
return lastValue;
},
/**
* Calculate the product of values in an object.
*
* @param {Object} obj - The object containing numeric values.
* @returns {number} The product of all values in the object.
*/
object_product: function(obj) {
let product = 1;
for (const key in obj) {
if (obj.hasOwnProperty(key) && typeof obj[key] === 'number') {
product *= obj[key];
}
}
return product;
},
/**
* Push one or more elements onto the end of object.
*
* @param {Object} obj - The object to push elements onto.
* @param {...any} elements - The elements to push onto the object.
* @returns {number} The new number of elements in the object.
*/
object_push: function(obj, ...elements) {
const keys = Object.keys(obj);
const newIndex = keys.length;
for (let i = 0; i < elements.length; i++) {
obj[newIndex + i] = elements[i];
}
return newIndex + elements.length;
},
/**
* Pick one or more random keys out of an object.
*
* @param {Object} obj - The object to pick random keys from.
* @param {number} [num = 1] - Optional. The number of random keys to pick.
* @returns {Array} An array containing the randomly picked keys.
*/
object_rand: function(obj, num = 1) {
const keys = Object.keys(obj);
const randomKeys = [];
while (randomKeys.length < num) {
const randomIndex = Math.floor(Math.random() * keys.length);
randomKeys.push(keys[randomIndex]);
}
return randomKeys;
},
/**
* Iteratively reduce the object to a single value using a callback function.
*
* @param {Object} obj - The object to reduce.
* @param {Function} callback - The callback function to apply.
* @param {any} [initialValue] - Optional. The initial value for the reduction.
* @returns {any} The final result of the reduction.
*/
object_reduce: function(obj, callback, initialValue) {
let accumulator = initialValue;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
accumulator = callback(accumulator, obj[key], key);
}
}
return accumulator;
},
/**
* Replaces elements from passed objects into the first object recursively.
*
* @param {Object} target - The target object to replace elements in.
* @param {...Object} sources - The source objects containing elements to replace.
* @returns {Object} The target object with replaced elements.
*/
object_replace_recursive: function(target, ...sources) {
for (const source of sources) {
for (const key in source) {
if (source.hasOwnProperty(key) && typeof source[key] === 'object' && source[key] !== null) {
if (!target.hasOwnProperty(key) || typeof target[key] !== 'object' || target[key] === null) {
target[key] = {};
}
target[key] = object_replace_recursive(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
return target;
},
/**
* Replaces elements from passed objects into the first object.
*
* @param {Object} target - The target object to replace elements in.
* @param {...Object} sources - The source objects containing elements to replace.
* @returns {Object} The target object with replaced elements.
*/
object_replace: function(target, ...sources) {
for (const source of sources) {
for (const key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
return target;
},
/**
* Return an object with elements in reverse order.
*
* @param {Object} obj - The object to reverse.
* @returns {Object} The reversed object.
*/
object_reverse: function(obj) {
const reversedObject = {};
const keys = Object.keys(obj).reverse();
for (const key of keys) {
reversedObject[key] = obj[key];
}
return reversedObject;
},
/**
* Searches the object for a given value and returns the first corresponding key if successful.
*
* @param {Object} obj - The object to search in.
* @param {any} searchValue - The value to search for in the object.
* @param {boolean} [strict=false] - Optional. Whether to do a strict (===) comparison when searching for the value.
* @returns {string|null} The key of the first occurrence of the value in the object, or null if not found.
*/
object_search: function(obj, searchValue, strict = false) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (strict && obj[key] === searchValue) {
return key;
} else if (!strict && obj[key] == searchValue) {
return key;
}
}
}
return null;
},
/**
* Shift an element off the beginning of object.
*
* @param {Object} obj - The object to shift from.
* @returns {any} The value of the shifted element.
*/
object_shift: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return undefined;
}
const firstKey = keys[0];
const firstValue = obj[firstKey];
delete obj[firstKey];
return firstValue;
},
/**
* Extract a slice of the object.
*
* @param {Object} obj - The object to slice.
* @param {number} [offset=0] - Optional. The starting index of the slice.
* @param {number} [length] - Optional. The length of the slice.
* @returns {Object} The sliced object.
*/
object_slice: function(obj, offset = 0, length) {
const slicedObject = {};
const keys = Object.keys(obj);
for (let i = offset; i < (length ? offset + length : keys.length); i++) {
const key = keys[i];
slicedObject[key] = obj[key];
}
return slicedObject;
},
/**
* Remove a portion of the object and replace it with something else.
*
* @param {Object} obj - The object to splice.
* @param {number} start - The starting index where the splice begins.
* @param {number} [deleteCount] - Optional. The number of elements to delete from the object.
* @param {...any} [items] - Optional. The elements to add to the object at the spliced position.
* @returns {Object} The spliced object.
*/
object_splice: function(obj, start, deleteCount, ...items) {
const keys = Object.keys(obj);
if (start < 0) {
start = keys.length + start;
}
const splicedObject = {};
for (let i = 0; i < start; i++) {
const key = keys[i];
splicedObject[key] = obj[key];
}
for (const item of items) {
splicedObject[start++] = item;
}
for (let i = start + deleteCount; i < keys.length; i++) {
const key = keys[i];
splicedObject[key] = obj[key];
}
return splicedObject;
},
/**
* Calculate the sum of values in an object.
*
* @param {Object} obj - The object containing numeric values.
* @returns {number} The sum of all values in the object.
*/
object_sum: function(obj) {
let sum = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key) && typeof obj[key] === 'number') {
sum += obj[key];
}
}
return sum;
},
/**
* Computes the difference of objects with additional index check, compares data by a callback function.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the data comparison.
* @returns {Object} An object containing values from obj1 that are not present in obj2 based on the callback function.
*/
object_udiff_assoc: function(obj1, obj2, callback) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key) && callback(obj1[key], obj2[key])) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the difference of objects with additional index check, compares data and indexes by a callback function.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} dataCallback - The callback function to perform the data comparison.
* @param {Function} keyCallback - The callback function to perform the index comparison.
* @returns {Object} An object containing values from obj1 that are not present in obj2 based on the callbacks.
*/
object_udiff_uassoc: function(obj1, obj2, dataCallback, keyCallback) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key) && keyCallback(key, key) && dataCallback(obj1[key], obj2[key])) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the difference of objects by using a callback function for data comparison.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the data comparison.
* @returns {Object} An object containing values from obj1 that are not present in obj2 based on the callback function.
*/
object_udiff: function(obj1, obj2, callback) {
const diffObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && !obj2.hasOwnProperty(key) && callback(obj1[key], obj2[key])) {
diffObject[key] = obj1[key];
}
}
return diffObject;
},
/**
* Computes the intersection of objects with additional index check, compares data by a callback function.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the data comparison.
* @returns {Object} An object containing values from obj1 that are present in obj2 based on the callback function.
*/
object_uintersect_assoc: function(obj1, obj2, callback) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key) && callback(obj1[key], obj2[key])) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Computes the intersection of objects with additional index check, compares data and indexes by separate callback functions.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} dataCallback - The callback function to perform the data comparison.
* @param {Function} keyCallback - The callback function to perform the index comparison.
* @returns {Object} An object containing values from obj1 that are present in obj2 based on the callbacks.
*/
object_uintersect_uassoc: function(obj1, obj2, dataCallback, keyCallback) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key) && keyCallback(key, key) && dataCallback(obj1[key], obj2[key])) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Computes the intersection of objects, compares data by a callback function.
*
* @param {Object} obj1 - The first object to compare.
* @param {Object} obj2 - The second object to compare.
* @param {Function} callback - The callback function to perform the data comparison.
* @returns {Object} An object containing values from obj1 that are present in obj2 based on the callback function.
*/
object_uintersect: function(obj1, obj2, callback) {
const intersectObject = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key) && callback(obj1[key], obj2[key])) {
intersectObject[key] = obj1[key];
}
}
return intersectObject;
},
/**
* Removes duplicate values from an object.
*
* @param {Object} obj - The object to remove duplicates from.
* @returns {Object} The object with duplicate values removed.
*/
object_unique: function(obj) {
const uniqueObject = {};
const uniqueValues = [];
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if (!uniqueValues.includes(value)) {
uniqueObject[key] = value;
uniqueValues.push(value);
}
}
}
return uniqueObject;
},
/**
* Prepend one or more elements to the beginning of an object.
*
* @param {Object} obj - The object to prepend elements to.
* @param {...any} elements - The elements to prepend to the object.
* @returns {number} The new number of elements in the object.
*/
object_unshift: function(obj, ...elements) {
const keys = Object.keys(obj);
const newIndex = elements.length;
for (let i = keys.length - 1; i >= 0; i--) {
obj[i + newIndex] = obj[i];
}
for (let i = 0; i < newIndex; i++) {
obj[i] = elements[i];
}
return keys.length + newIndex;
},
/**
* Return all the values of an object.
*
* @param {Object} obj - The object to get the values from.
* @returns {Array} An array containing the values of the object.
*/
object_values: function(obj) {
const values = [];
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
values.push(obj[key]);
}
}
return values;
},
/**
* Apply a user function recursively to every member of an object.
*
* @param {Object} obj - The object to apply the function to.
* @param {Function} callback - The callback function to apply.
* @param {any} [userdata] - Optional. User-defined data to pass to the callback function.
* @returns {boolean} True on success, false on failure.
*/
object_walk_recursive: function(obj, callback, userdata) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const result = callback(obj[key], key, userdata);
if (typeof result === 'object' && !Array.isArray(result)) {
if (!object_walk_recursive(result, callback, userdata)) {
return false;
}
} else if (result === false) {
return false;
}
}
}
return true;
},
/**
* Apply a user supplied function to every member of an object.
*
* @param {Object} obj - The object to apply the function to.
* @param {Function} callback - The callback function to apply.
* @param {any} [userdata] - Optional. User-defined data to pass to the callback function.
* @returns {boolean} True on success, false on failure.
*/
object_walk: function(obj, callback, userdata) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const result = callback(obj[key], key, userdata);
if (result === false) {
return false;
}
}
}
return true;
},
/**
* Create an object.
*
* @param {...any} elements - Optional. The elements to include in the object.
* @returns {Object} The created object.
*/
object: function(...elements) {
const createdObject = {};
for (let i = 0; i < elements.length; i += 2) {
const key = elements[i];
const value = elements[i + 1];
createdObject[key] = value;
}
return createdObject;
},
/**
* Sort an object in descending order and maintain index association.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
arsort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
if (obj[a] < obj[b]) {
return 1;
}
if (obj[a] > obj[b]) {
return -1;
}
return 0;
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Sort an object in ascending order and maintain index association.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
asort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
if (obj[a] < obj[b]) {
return -1;
}
if (obj[a] > obj[b]) {
return 1;
}
return 0;
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Create an object containing variables and their values.
*
* @param {...any} vars - The variables and their values to include in the object.
* @returns {Object} The created object.
*/
compact: function(...vars) {
const compactedObject = {};
for (let i = 0; i < vars.length; i += 2) {
const key = vars[i];
const value = vars[i + 1];
compactedObject[key] = value;
}
return compactedObject;
},
/**
* Counts all elements in an object or in a Countable object.
*
* @param {Object|Countable} obj - The object to count elements in.
* @param {number} [mode=COUNT_NORMAL] - Optional. The mode for counting.
* @returns {number} The number of elements in the object.
*/
count: function(obj, mode = COUNT_NORMAL) {
if (mode === COUNT_RECURSIVE) {
let count = 0;
object_walk_recursive(obj, function() {
count++;
});
return count;
} else {
return Object.keys(obj).length;
}
},
/**
* Return the current element in an object.
*
* @param {Object} obj - The object to get the current element from.
* @returns {any} The current element value.
*/
current: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return undefined;
}
const currentKey = keys[0];
return obj[currentKey];
},
/**
* Return the current key and value pair from an object and advance the object cursor.
*
* @param {Object} obj - The object to get the current key and value pair from.
* @returns {Object} An object containing the current key and value, and then advances the cursor.
*/
each: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return false;
}
const currentKey = keys[0];
const currentValue = obj[currentKey];
delete obj[currentKey];
return { key: currentKey, value: currentValue };
},
/**
* Set the internal pointer of an object to its last element.
*
* @param {Object} obj - The object to set the internal pointer in.
* @returns {any} The value of the last element in the object.
*/
end: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return undefined;
}
const lastKey = keys[keys.length - 1];
return obj[lastKey];
},
/**
* Import variables into the current symbol table from an object.
*
* @param {Object} obj - The object containing variables and their values.
* @returns {boolean} True on success, false on failure.
*/
extract: function(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
this[key] = obj[key];
}
}
return true;
},
/**
* Checks if a value exists in an object.
*
* @param {any} value - The value to check for.
* @param {Object} obj - The object to check in.
* @returns {boolean} True if the value exists in the object, false otherwise.
*/
in_object: function(value, obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key] === value) {
return true;
}
}
return false;
},
/**
* Fetch a key from an object.
*
* @param {number} index - The index of the key to fetch.
* @param {Object} obj - The object to fetch the key from.
* @returns {string|boolean} The key at the specified index or false if the index is out of range.
*/
key: function(index, obj) {
const keys = Object.keys(obj);
if (index < 0 || index >= keys.length) {
return false;
}
return keys[index];
},
/**
* Sort an object by key in descending order.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
krsort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
if (a > b) {
return -1;
}
if (a < b) {
return 1;
}
return 0;
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Sort an object by key in ascending order.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
ksort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Assign variables as if they were an object.
*
* @param {any} vars - The variables to assign.
* @returns {Object} The object containing the assigned variables.
*/
list: function(...vars) {
const listObject = {};
for (let i = 0; i < vars.length; i++) {
listObject[i] = vars[i];
}
return listObject;
},
/**
* Sort an object using a case insensitive "natural order" algorithm.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
natcasesort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
return a.localeCompare(b, undefined, { sensitivity: 'base' });
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Sort an object using a "natural order" algorithm.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
natsort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
return a.localeCompare(b);
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Advance the internal pointer of an object.
*
* @param {Object} obj - The object to advance the pointer in.
* @returns {boolean} True on success, false on failure.
*/
next: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return false;
}
delete obj[keys[0]];
return true;
},
/**
* Alias of current.
*
* @param {Object} obj - The object to get the current element from.
* @returns {any} The current element value.
*/
pos: function(obj) {
return this.current(obj);
},
/**
* Rewind the internal object pointer.
*
* @param {Object} obj - The object to rewind the pointer in.
* @returns {boolean} True on success, false on failure.
*/
prev: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return false;
}
const firstKey = keys[0];
const firstValue = obj[firstKey];
delete obj[firstKey];
obj[firstKey] = firstValue;
return true;
},
/**
* Create an object containing a range of elements.
*
* @param {number} start - The starting value of the range.
* @param {number} end - The ending value of the range.
* @param {number} [step=1] - Optional. The step value for the range.
* @returns {Object} The created object containing the range elements.
*/
range: function(start, end, step = 1) {
const rangeObject = {};
for (let i = start; i <= end; i += step) {
rangeObject[i] = i;
}
return rangeObject;
},
/**
* Set the internal pointer of an object to its first element.
*
* @param {Object} obj - The object to set the internal pointer in.
* @returns {any} The value of the first element in the object.
*/
reset: function(obj) {
const keys = Object.keys(obj);
if (keys.length === 0) {
return undefined;
}
const firstKey = keys[0];
return obj[firstKey];
},
/**
* Sort an object in descending order.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
rsort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
if (obj[a] < obj[b]) {
return 1;
}
if (obj[a] > obj[b]) {
return -1;
}
return 0;
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Shuffle the elements of an object.
*
* @param {Object} obj - The object to shuffle.
* @returns {boolean} True on success, false on failure.
*/
shuffle: function(obj) {
const values = Object.values(obj);
let currentIndex = values.length, randomIndex, temporaryValue;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
temporaryValue = values[currentIndex];
values[currentIndex] = values[randomIndex];
values[randomIndex] = temporaryValue;
}
// Reconstruct the object with shuffled values.
const shuffledObject = {};
let i = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
shuffledObject[key] = values[i];
i++;
}
}
return shuffledObject;
},
/**
* Alias of count.
*
* @param {Object|Countable} obj - The object to count elements in.
* @param {number} [mode=COUNT_NORMAL] - Optional. The mode for counting.
* @returns {number} The number of elements in the object.
*/
sizeof: function(obj, mode = COUNT_NORMAL) {
return this.count(obj, mode);
},
/**
* Sort an object in ascending order.
*
* @param {Object} obj - The object to sort.
* @returns {boolean} True on success, false on failure.
*/
sort: function(obj) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
if (obj[a] < obj[b]) {
return -1;
}
if (obj[a] > obj[b]) {
return 1;
}
return 0;
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Sort an object with a user-defined comparison function and maintain index association.
*
* @param {Object} obj - The object to sort.
* @param {Function} compareFunction - The comparison function to use for sorting.
* @returns {boolean} True on success, false on failure.
*/
uasort: function(obj, compareFunction) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
return compareFunction(obj[a], obj[b]);
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Sort an object by keys using a user-defined comparison function.
*
* @param {Object} obj - The object to sort.
* @param {Function} compareFunction - The comparison function to use for sorting.
* @returns {boolean} True on success, false on failure.
*/
uksort: function(obj, compareFunction) {
const keys = Object.keys(obj);
keys.sort(function(a, b) {
return compareFunction(a, b);
});
const sortedObject = {};
for (const key of keys) {
sortedObject[key] = obj[key];
}
return sortedObject;
},
/**
* Sort an object by values using a user-defined comparison function.
*
* @param {Object} obj - The object to sort.
* @param {Function} compareFunction - The comparison function to use for sorting.
* @returns {boolean} True on success, false on failure.
*/
usort: function(obj, compareFunction) {
const values = Object.values(obj);
values.sort(function(a, b) {
return compareFunction(a, b);
});
const sortedObject = {};
let i = 0;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
sortedObject[key] = values[i];
i++;
}
}
return sortedObject;
}
},
/**
* NOYPI math funcs
* @namespace
* @memberOf noypiJS
*/
math : {/**
* Returns the absolute value of a number.
*
* @param {number} num - The number to calculate the absolute value for.
* @returns {number} The absolute value of the given number.
*/
abs: function(num) {
return Math.abs(num);
},
/**
* Returns the arc cosine of a number in radians.
*
* @param {number} num - The number to calculate the arc cosine for.
* @returns {number} The arc cosine in radians.
*/
acos: function(num) {
return Math.acos(num);
},
/**
* Returns the inverse hyperbolic cosine of a number.
*
* @param {number} num - The number to calculate the inverse hyperbolic cosine for.
* @returns {number} The inverse hyperbolic cosine.
*/
acosh: function(num) {
return Math.acosh(num);
},
/**
* Returns the arc sine of a number in radians.
*
* @param {number} num - The number to calculate the arc sine for.
* @returns {number} The arc sine in radians.
*/
asin: function(num) {
return Math.asin(num);
},
/**
* Returns the inverse hyperbolic sine of a number.
*
* @param {number} num - The number to calculate the inverse hyperbolic sine for.
* @returns {number} The inverse hyperbolic sine.
*/
asinh: function(num) {
return Math.asinh(num);
},
/**
* Returns the angle (in radians) from the X-axis to a point (y, x).
*
* @param {number} y - The Y-coordinate of the point.
* @param {number} x - The X-coordinate of the point.
* @returns {number} The arc tangent of y/x in radians.
*/
atan2: function(y, x) {
return Math.atan2(y, x);
},
/**
* Returns the arc tangent of a number in radians.
*
* @param {number} num - The number to calculate the arc tangent for.
* @returns {number} The arc tangent in radians.
*/
atan: function(num) {
return Math.atan(num);
},
/**
* Returns the inverse hyperbolic tangent of a number.
*
* @param {number} num - The number to calculate the inverse hyperbolic tangent for.
* @returns {number} The inverse hyperbolic tangent.
*/
atanh: function(num) {
return Math.atanh(num);
},
/**
* Converts a number between arbitrary bases.
*
* @param {string} num - The number to convert as a string.
* @param {number} fromBase - The base of the number to convert from.
* @param {number} toBase - The base to convert the number to.
* @returns {string} The converted number as a string.
*/
base_convert: function(num, fromBase, toBase) {
return parseInt(num, fromBase).toString(toBase);
},
/**
* Converts a binary number to its decimal equivalent.
*
* @param {string} binaryStr - The binary number as a string.
* @returns {number} The decimal equivalent of the binary number.
*/
bindec: function(binaryStr) {
return parseInt(binaryStr, 2);
},
/**
* Rounds fractions up to the nearest integer.
*
* @param {number} num - The number to round up.
* @returns {number} The rounded-up integer.
*/
ceil: function(num) {
return Math.ceil(num);
},
/**
* Returns the cosine of a number.
*
* @param {number} num - The number to calculate the cosine for.
* @returns {number} The cosine of the number.
*/
cos: function(num) {
return Math.cos(num);
},
/**
* Returns the hyperbolic cosine of a number.
*
* @param {number} num - The number to calculate the hyperbolic cosine for.
* @returns {number} The hyperbolic cosine.
*/
cosh: function(num) {
return Math.cosh(num);
},
/**
* Converts a decimal number to its binary equivalent.
*
* @param {number} decimalNum - The decimal number to convert.
* @returns {string} The binary representation of the decimal number.
*/
decbin: function(decimalNum) {
return (decimalNum >>> 0).toString(2);
},
/**
* Converts a decimal number to its hexadecimal equivalent.
*
* @param {number} decimalNum - The decimal number to convert.
* @returns {string} The hexadecimal representation of the decimal number.
*/
dechex: function(decimalNum) {
return decimalNum.toString(16);
},
/**
* Converts a decimal number to its octal equivalent.
*
* @param {number} decimalNum - The decimal number to convert.
* @returns {string} The octal representation of the decimal number.
*/
decoct: function(decimalNum) {
return decimalNum.toString(8);
},
/**
* Converts degrees to radians.
*
* @param {number} degrees - The number in degrees to convert to radians.
* @returns {number} The equivalent angle in radians.
*/
deg2rad: function(degrees) {
return degrees * (Math.PI / 180);
},
/**
* Calculates the value of 'e' raised to the power of a number.
*
* @param {number} num - The exponent.
* @returns {number} The result of 'e' raised to the power of the exponent.
*/
exp: function(num) {
return Math.exp(num);
},
/**
* Calculates exp(num) - 1, computed in a way that is accurate even when num is close to zero.
*
* @param {number} num - The number.
* @returns {number} The result of exp(num) - 1.
*/
expm1: function(num) {
return Math.expm1(num);
},
/**
* Divides two numbers according to IEEE 754 rules.
*
* @param {number} dividend - The dividend.
* @param {number} divisor - The divisor.
* @returns {number} The result of dividing the dividend by the divisor.
*/
fdiv: function(dividend, divisor) {
return dividend / divisor;
},
/**
* Rounds fractions down to the nearest integer.
*
* @param {number} num - The number to round down.
* @returns {number} The rounded-down integer.
*/
floor: function(num) {
return Math.floor(num);
},
/**
* Returns the floating-point remainder (modulo) of dividing two numbers.
*
* @param {number} dividend - The dividend.
* @param {number} divisor - The divisor.
* @returns {number} The remainder of dividing the dividend by the divisor.
*/
fmod: function(dividend, divisor) {
return dividend % divisor;
},
/**
* Converts a hexadecimal number to its decimal equivalent.
*
* @param {string} hexStr - The hexadecimal number as a string.
* @returns {number} The decimal equivalent of the hexadecimal number.
*/
hexdec: function(hexStr) {
return parseInt(hexStr, 16);
},
/**
* Calculates the length of the hypotenuse of a right-angle triangle.
*
* @param {number} x - The length of one side of the triangle.
* @param {number} y - The length of the other side of the triangle.
* @returns {number} The length of the hypotenuse.
*/
hypot: function(x, y) {
return Math.hypot(x, y);
},
/**
* Performs integer division.
*
* @param {number} dividend - The dividend.
* @param {number} divisor - The divisor.
* @returns {number} The result of dividing the dividend by the divisor, rounded towards zero.
*/
intdiv: function(dividend, divisor) {
return Math.trunc(dividend / divisor);
},
/**
* Checks if a value is a legal finite number.
*
* @param {number} num - The value to check.
* @returns {boolean} True if the value is finite, false otherwise.
*/
is_finite: function(num) {
return Number.isFinite(num);
},
/**
* Checks if a value is infinite.
*
* @param {number} num - The value to check.
* @returns {boolean} True if the value is infinite, false otherwise.
*/
is_infinite: function(num) {
return !Number.isFinite(num);
},
/**
* Checks if a value is not a number (NaN).
*
* @param {number} num - The value to check.
* @returns {boolean} True if the value is NaN, false otherwise.
*/
is_nan: function(num) {
return Number.isNaN(num);
},
/**
* Returns the base-10 logarithm of a number.
*
* @param {number} num - The number to calculate the base-10 logarithm for.
* @returns {number} The base-10 logarithm of the number.
*/
log10: function(num) {
return Math.log10(num);
},
/**
* Returns log(1 + num), computed in a way that is accurate even when num is close to zero.
*
* @param {number} num - The number.
* @returns {number} The result of log(1 + num).
*/
log1p: function(num) {
return Math.log1p(num);
},
/**
* Returns the natural logarithm (base 'e') of a number.
*
* @param {number} num - The number to calculate the natural logarithm for.
* @returns {number} The natural logarithm of the number.
*/
log: function(num) {
return Math.log(num);
},
/**
* Finds the highest value in an array or a set of values.
*
* @param {...number} values - The values to compare.
* @returns {number} The highest value.
*/
max: function(...values) {
return Math.max(...values);
},
/**
* Finds the lowest value in an array or a set of values.
*
* @param {...number} values - The values to compare.
* @returns {number} The lowest value.
*/
min: function(...values) {
return Math.min(...values);
},
/**
* Converts an octal number to its decimal equivalent.
*
* @param {string} octalStr - The octal number as a string.
* @returns {number} The decimal equivalent of the octal number.
*/
octdec: function(octalStr) {
return parseInt(octalStr, 8);
},
/**
* Get the value of pi (π).
*
* @returns {number} The mathematical constant pi (π).
*/
pi: function() {
return Math.PI;
},
/**
* Returns the result of raising a number to a given power.
*
* @param {number} base - The base number.
* @param {number} exponent - The exponent.
* @returns {number} The result of the exponential expression.
*/
pow: function(base, exponent) {
return Math.pow(base, exponent);
},
/**
* Converts radians to degrees.
*
* @param {number} radians - The angle in radians to convert to degrees.
* @returns {number} The equivalent angle in degrees.
*/
rad2deg: function(radians) {
return radians * (180 / Math.PI);
},
/**
* Rounds a floating-point number to the nearest integer.
*
* @param {number} num - The number to round.
* @returns {number} The rounded integer.
*/
round: function(num) {
return Math.round(num);
},
/**
* Returns the sine of a number.
*
* @param {number} num - The number to calculate the sine for.
* @returns {number} The sine of the number.
*/
sin: function(num) {
return Math.sin(num);
},
/**
* Returns the hyperbolic sine of a number.
*
* @param {number} num - The number to calculate the hyperbolic sine for.
* @returns {number} The hyperbolic sine.
*/
sinh: function(num) {
return Math.sinh(num);
},
/**
* Returns the square root of a number.
*
* @param {number} num - The number to calculate the square root for.
* @returns {number} The square root of the number.
*/
sqrt: function(num) {
return Math.sqrt(num);
},
/**
* Returns the tangent of a number.
*
* @param {number} num - The number to calculate the tangent for.
* @returns {number} The tangent of the number.
*/
tan: function(num) {
return Math.tan(num);
},
/**
* Returns the hyperbolic tangent of a number.
*
* @param {number} num - The number to calculate the hyperbolic tangent for.
* @returns {number} The hyperbolic tangent.
*/
tanh: function(num) {
return Math.tanh(num);
},
},
/**
* NOYPI string funcs
* @namespace
* @memberOf noypiJS
*/
str : {
/**
* Returns a character from the specified ASCII value. The ASCII value can be specified in decimal, octal, or hex values. Octal values are defined by a leading 0, while hex values are defined by a leading 0x.
*
* @param {number} ascii - can be specified in decimal, octal, or hex values, any numeric value.
* @return {string} - The ascii character in index `ascii`.
* @example
* var chrascii = noypiJS.str.chr(42);
*/
chr : function(asciiValue) {
return String.fromCharCode(asciiValue)
},
/**
* Calculates distance between two strings
*
* @param {string} str1 - String to be compared from
* @param {string} str2 - String to be compared to
* @return {number} - Levenshtein distance
*
* @example
* var distance = noypiJS.str.levenshtein("advice","Advise");
*/
levenshtein : function (str1, str2) {
const m = str1.length;
const n = str2.length;
// Create a matrix to store the distances
const dp = Array.from(Array(m + 1), () => Array(n + 1).fill(0));
// Initialize the first row and column
for (let i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (let j = 0; j <= n; j++) {
dp[0][j] = j;
}
// Fill in the matrix using dynamic programming
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
dp[i][j] = Math.min(
dp[i - 1][j] + 1, // Deletion
dp[i][j - 1] + 1, // Insertion
dp[i - 1][j - 1] + cost // Substitution
);
}
}
// The final value in the matrix represents the Levenshtein distance
return dp[m][n];
},
/**
* Replaces string `search` in string `string` to string `replacement`
*
* @param {string} search - Needle
* @param {string} replacement - What to replace the needle (search)
* @param {string} string - Haystack
* @return {string} - Replaced string
*
* @example
* var replaced_str = noypiJS.str.ireplace("easy","tedious","This is very easy!");
*/
ireplace : function (search, replacement, string) {
// Escape special characters in the search string
search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Create a regular expression with the 'i' flag for case-insensitive search
var regex = new RegExp(search, 'gi');
// Use the replace method to perform the replacement
var result = string.replace(regex, replacement);
return result;
},
/**
* Pads `inputString` to `length` using mode `padType`.
*
* @param {string} search - Needle
* @param {int} replacement - What to replace the needle (search)
* @param {string} string - Three modes: "STR_PAD_LEFT" pads to left only; 'STR_PAD_RIGHT' right side only; 'STR_PAD_BOTH' means both sides be padded equally.
* @return {string} - Padded string
*
* @example
* var padded_str = noypiJS.str.pad("0",5,"STR_PAD_LEFT");
*/
pad : function (inputString, length, padString = ' ', padType = 'STR_PAD_RIGHT') {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
if (typeof length !== 'number') {
throw new Error('Length must be a number.');
}
if (padType !== 'STR_PAD_LEFT' && padType !== 'STR_PAD_RIGHT' && padType !== 'STR_PAD_BOTH') {
throw new Error('Invalid pad type. Use STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH.');
}
if (length <= inputString.length) {
return inputString;
}
const padLength = length - inputString.length;
const leftPadding = Math.floor(padLength / 2);
const rightPadding = Math.ceil(padLength / 2);
let paddedString = '';
if (padType === 'STR_PAD_LEFT' || padType === 'STR_PAD_BOTH') {
paddedString += padString.repeat(leftPadding);
}
paddedString += inputString;
if (padType === 'STR_PAD_RIGHT' || padType === 'STR_PAD_BOTH') {
paddedString += padString.repeat(rightPadding);
}
return paddedString;
},
/**
* Repeats `inputString` to `repeat` times
*
* @param {string} inputString - Needle
* @param {number} repeat - What to replace the needle (search)
* @return {string} - Repeated string
*
* @example
* var padded_str = noypiJS.str.pad("0",5,"STR_PAD_LEFT");
*/
repeat: function (inputString, repeat) {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
if (typeof repeat !== 'number' || repeat < 0) {
throw new Error('Repeat must be a non-negative number.');
}
return inputString.repeat(repeat);
},
/**
* Encodes `inputString` to rot13,
*
* @param {string} inputString - String to be encoded
* @return {string} - Encoded string
*
* @example
* var rot13_str = noypiJS.str.rot13("hello world");
*/
rot13: function (inputString) {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
// Define a function for ROT13 encoding
function rot13char(char) {
const aCode = 'a'.charCodeAt(0);
const ACode = 'A'.charCodeAt(0);
const zCode = 'z'.charCodeAt(0);
const ZCode = 'Z'.charCodeAt(0);
const charCode = char.charCodeAt(0);
if (char >= 'a' && char <= 'z') {
return String.fromCharCode(((charCode - aCode + 13) % 26) + aCode);
} else if (char >= 'A' && char <= 'Z') {
return String.fromCharCode(((charCode - ACode + 13) % 26) + ACode);
} else {
return char;
}
}
// Apply ROT13 encoding to each character in the string
const encodedArray = inputString.split('').map(rot13char);
// Join the encoded characters back into a string
const encodedString = encodedArray.join('');
return encodedString;
},
/**
* Case sensitive replace of `search` to `replacement` using haystack `string`,
*
* @param {string} search - Needle
* @param {string} replacement - What to replace the needle (search)
* @param {string} string - Haystack
* @return {string} - Replaced string
*
* @example
* var replaced_str = noypiJS.str.ireplace("easy","tedious","This is very easy!");
*/
replace : function (search, replacement, string) {
// Escape special characters in the search string
search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Create a regular expression with the 'i' flag for case-insensitive search
var regex = new RegExp(search, 'gi');
// Use the replace method to perform the replacement
var result = string.replace(regex, replacement);
return result;
},
/**
* Split `inputString` by chars. The function splits by one char on default.
*
* @param {string} inputString - Haystack
* @param {number} length - How many chars in each chunk
* @return {array} - Chunked array
*
* @example
* var chunky_str = noypiJS.str.split("all the world's a stage",2);
*/
split: function (inputString, length = 1) {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
if (typeof length !== 'number' || length < 1) {
throw new Error('Length must be a positive number.');
}
const result = [];
for (let i = 0; i < inputString.length; i += length) {
result.push(inputString.slice(i, i + length));
}
return result;
},
/**
* Counts the number of words in a string and provides various return options.
*
* @param {string} inputString - The string to check.
* @param {number} [returnType=0] - Specifies the return value of the function:
* - 0 (default): Returns the number of words found.
* - 1: Returns an array with the words from the string.
* - 2: Returns an array where the key is the position of the word in the string, and the value is the actual word.
* @param {string} [charList] - Specifies special characters to be considered as words.
* @returns {number|string[]|Object} Depending on the returnType parameter:
* - If returnType is 0, returns the number of words found.
* - If returnType is 1, returns an array with the words from the string.
* - If returnType is 2, returns an object where the key is the position of the word in the string, and the value is the actual word.
*/
word_count: function (inputString, returnOption = 0, charList = null) {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
if (returnOption !== 0 && returnOption !== 1 && returnOption !== 2) {
throw new Error('Invalid return option. Use 0, 1, or 2.');
}
if (charList !== null && typeof charList !== 'string') {
throw new Error('Character list must be a string or null.');
}
const words = inputString.split(/\s+/);
if (charList !== null) {
// Remove specified characters from each word
for (let i = 0; i < words.length; i++) {
const word = words[i];
const regex = new RegExp(`[${charList}]`, 'g');
words[i] = word.replace(regex, '');
}
}
if (returnOption === 1) {
return words;
} else if (returnOption === 2) {
const wordMap = {};
for (let i = 0; i < words.length; i++) {
wordMap[i] = words[i];
}
return wordMap;
} else {
return words.length;
}
},
/**
* Converts a string to lowercase.
*
* @param {string} inputString - The string to convert.
* @returns {string} The input string converted to lowercase.
*/
strtolower: function (inputString) {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
return inputString.toLowerCase();
},
/**
* Converts a string to uppercase.
*
* @param {string} inputString - The string to convert.
* @returns {string} The input string converted to uppercase.
*/
strtoupper: function (inputString) {
if (typeof inputString !== 'string') {
throw new Error('Input must be a string.');
}
return inputString.toUpperCase();
},
/**
* Reverses a string.
*
* @param {string} string - The string to reverse.
* @returns {string} The reversed string.
*/
reverseString: function(string) {
// Reverses the string
return string.split('').reverse().join('');
},
/**
* Returns the length of a string.
*
* @param {string} string - The string to check.
* @returns {number} The length of the string (in bytes) on success, or 0 if the string is empty.
*/
strlen: function(string) {
return string.length;
},
/**
* Wraps a string into new lines when it reaches a specific length.
*
* @param {string} string - The string to break up into lines.
* @param {number} [width=75] - Optional. The maximum line width. Default is 75.
* @param {string} [break="\n"] - Optional. The characters to use as breaks. Default is "\n".
* @param {boolean} [cut=false] - Optional. Whether words longer than the specified width should be wrapped.
* - `false` (Default): No-wrap.
* - `true`: Wrap.
* @returns {string} The word-wrapped string.
*/
wordwrap: function(string, width = 75, breakChar = "\n", cut = false) {
const regex = cut ? new RegExp(`.{1,${width}}|.{1,${width}}$`, 'g') : new RegExp(`.{1,${width}}`, 'g');
return string.match(regex).join(breakChar);
},
/**
* Converts the first character of a string to uppercase.
*
* @param {string} string - The string to convert.
* @returns {string} The string with the first character in uppercase.
*/
ucfirst: function(string) {
if (string.length === 0) {
return string; // Return the empty string if no characters to capitalize.
}
return string.charAt(0).toUpperCase() + string.slice(1);
},
/**
* Returns a string from the elements of an array, joined by a specified separator.
*
* @param {string} [separator=""] - Optional. Specifies what to put between the array elements. Default is an empty string.
* @param {Array} array - The array to join to a string.
* @returns {string} The string created by joining the array elements with the separator.
*/
implode: function(separator = "", array) {
if (!Array.isArray(array)) {
throw new TypeError("The second argument must be an array.");
}
return array.join(separator);
},
/**
* Removes whitespace and specified characters from both sides of a string.
*
* @param {string} string - The string to trim.
* @param {string} [charlist="\0\t\n\x0B\r "] - Optional. Specifies which characters to remove from the string.
* @returns {string} The trimmed string.
*/
trim: function(string, charlist = "\0\t\n\x0B\r ") {
const pattern = `[${charlist}]`;
const regex = new RegExp(`^${pattern}+|${pattern}+$`, 'g');
return string.replace(regex, '');
},
/**
* Counts the number of times a substring occurs in a string.
*
* @param {string} string - The string to check.
* @param {string} substring - The substring to search for.
* @param {number} [start=0] - Optional. Specifies where in the string to start searching.
* If negative, it starts counting from the end of the string.
* @param {number} [length] - Optional. Specifies the length of the search.
* @returns {number} The count of occurrences of the substring in the string.
*/
substr_count: function(string, substring, start = 0, length) {
if (typeof length === 'undefined') {
length = string.length - start;
}
const sub = string.substr(start, length);
let count = 0;
let index = sub.indexOf(substring);
while (index !== -1) {
count++;
index = sub.indexOf(substring, index + 1);
}
return count;
},
},
}
export default noypiJS;
// module.exports = noypiJS