Const
Generated using TypeDoc
Appends the elms
to the target
where the elms may be an array, a single object
+
Appends the elms
to the target
where the elms may be an array, a single object
or an iterator object
The target array
-The item, array of items an iterable or iterator object of items to add to the target
+The passed in target array
let theArray = arrAppend([], 1);
arrAppend(theArray, [ 2, 3, 4 ]);
arrAppend(theArray, [ "a", "b", "c" ]);
// theArray is now [ 1, 2, 3, 4, "a", "b", "c" ]
// Adding a single value
arrAppend([], undefined); // []
arrAppend([], 0); // [ 0 ]
arrAppend([1], undefined); // [ 1 ]
arrAppend([1], 2); // [ 1, 2 ]
// Adding an array
arrAppend([], [] as number[]); // []
arrAppend([], [0]); // [ 0 ]
arrAppend([1], []); // [ 1 ]
arrAppend([1], [2]); // [ 1, 2 ]
// Adding with an iterator
arrAppend([], ([] as number[]).values()); // []
arrAppend([], [0].values()); // [ 0 ]
arrAppend([1], [].keys()); // [ 1 ]
arrAppend([1], [2].values()); // [ 1, 2 ]
arrAppend([1], [2].keys()); // [ 1, 0 ] - 0 is from the index from the first element
-Generated using TypeDoc
Generated using TypeDoc
The arrContains() method determines whether an array contains a certain value among its +
The arrContains() method determines whether an array contains a certain value among its entries, returning true or false as appropriate.
-The array or array like object of elements to be searched.
-The value to search for
-Optional
fromIndex: numberThe optional Zero-based index at which to start searching, converted to an integer.
+The array or array like object of elements to be searched.
+The value to search for
+Optional
fromIndex: numberThe optional Zero-based index at which to start searching, converted to an integer.
0.8.0
arrContains([1, 2, 3], 2); // true
arrContains([1, 2, 3], 4); // false
arrContains([1, 2, 3], 3, 3); // false
arrContains([1, 2, 3], 3, -1); // true
arrContains([1, 2, NaN], NaN); // true
arrContains(["1", "2", "3"], 3 as any); // false
// Array Like
arrContains({ length: 3, 0: 1, 1: 2, 2: 3 }, 2); // true
arrContains({ length: 3, 0: 1, 1: 2, 2: 3 }, 4); // false
arrContains({ length: 3, 0: 1, 1: 2, 2: 3 }, 3, 3); // false
arrContains({ length: 3, 0: 1, 1: 2, 2: 3 }, 3, -1); // true
arrContains({ length: 3, 0: 1, 1: 2, 2: NaN }, NaN); // true
arrContains({ length: 3, 0: "1", 1: "2", 2: "3" }, 3 as any); // false
-Generated using TypeDoc
Generated using TypeDoc
The arrEvery() method is an iterative method. It calls a provided callbackFn function once for +
The arrEvery() method is an iterative method. It calls a provided callbackFn function once for each element in an array, until the callbackFn returns a falsy value. If such an element is found, arrEvery() immediately returns false and stops iterating through the array. Otherwise, if callbackFn returns a truthy value for all elements, every() returns true.
-The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
true
if the callbackFn returns a truthy
value for every array elements. Otherwise false
.
0.8.0
function isBigEnough<T>(element: T, index: number, array: T[]) {
return element >= 10;
}
arrEvery([12, 5, 8, 130, 44], isBigEnough); // false
arrEvery([12, 54, 18, 130, 44], isBigEnough); // true
const isSubset = <T>(array1: T[], array2: T[]) => arrEvery(array2, (element) => arrIncludes(array1, element));
isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6]); // true
isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7]); // false
arrEvery([1, , 3], (x) => x !== undefined); // true
arrEvery([2, , 2], (x) => x === 2); // true
// Array Like combinations
isSubset([1, 2, 3, 4, 5, 6, 7], { length: 3, 0: 5, 1: 7, 2: 6}); // true
isSubset([1, 2, 3, 4, 5, 6, 7], { length: 3, 0: 5, 1: 8, 2: 7}); // false
isSubset({ length: 7, 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7 }, [ 5, 7, 6 ]); // true
isSubset({ length: 7, 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7 }, [5, 8, 7]); // false
isSubset({ length: 7, 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7 }, { length: 3, 0: 5, 1: 7, 2: 6}); // true
isSubset({ length: 7, 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7 }, { length: 3, 0: 5, 1: 8, 2: 7}); // false
-Generated using TypeDoc
Generated using TypeDoc
The arrFilter() method creates a shallow copy of a portion of a given array, filtered down to just the elements +
The arrFilter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
The filter() method is an iterative method. It calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a truthy value. Array elements @@ -16,17 +16,17 @@
callbackFn
will be the value at the time that element gets visited. Deleted elements are not visited.The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
A shallow copy of a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.
0.8.0
function isBigEnough<T>(value: T) {
return value >= 10;
}
const filtered = arrFilter([12, 5, 8, 130, 44], isBigEnough);
// filtered is [12, 130, 44]
const arrayLikeFiltered = arrFilter({ length: 5, 0: 12, 1: 5, 2: 8, 3: 130, 4: 44}, isBigEnough);
// arrayLikeFiltered is [12, 130, 44]
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
console.log(arrFilter(array, isPrime)); // [2, 3, 5, 7, 11, 13]
-Generated using TypeDoc
Generated using TypeDoc
The arrFind() method returns the first element in the provided array that satisfies +
The arrFind() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
callbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they
were undefined.
The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
0.8.0
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
function isCherries(fruit) {
return fruit.name === "cherries";
}
console.log(arrFind(inventory, isCherries));
// { name: 'cherries', quantity: 5 }
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log(arrFind([4, 6, 8, 12], isPrime)); // undefined, not found
console.log(arrFind([4, 5, 8, 12], isPrime)); // 5
// Array Like
console.log(arrFind({ length: 4, 0: 4, 1: 6, 2: 8, 3: 12 }, isPrime)); // undefined, not found
console.log(arrFind({ length: 4:, 0: 4, 1: 5, 2: 8, 3: 12 }, isPrime)); // 5
-Generated using TypeDoc
Generated using TypeDoc
The arrFindIndex() method returns the index of the first element in an array that satisfies the provided testing +
The arrFindIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
The arrFindIndex() is an iterative method. It calls a provided callbackFn function once for each element in an
array in ascending-index order, until callbackFn returns a truthy value. arrFindIndex() then returns the index
@@ -14,15 +14,15 @@
If an existing, yet-unvisited element of the array is changed by callbackFn
, its value passed to the callbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined.
-
The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
The index of the first element in the array that passes the test. Otherwise, -1.
0.8.0
const inventory: Array<{ name: string, quantity: number}> = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 }
];
function isCherries(fruit: { name: string, quantity: number}) {
return fruit.name === "cherries";
}
arrFindIndex(inventory, isCherries); // 2
function isPrime(element: number) {
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
arrFindIndex([4, 6, 8, 9, 12], isPrime) // -1
arrFindIndex([4, 6, 7, 9, 12], isPrime) // 2
// Array Like
arrFindIndex({ length: 5, 0: 4, 1: 6, 2: 8, 3: 9, 4: 12 }, isPrime) // -1
arrFindIndex({ length: 5:, 0: 4, 1: 6, 2: 7, 3: 9, 4: 12 }, isPrime) // 2
-Generated using TypeDoc
Generated using TypeDoc
The arrFindLast() method iterates the array in reverse order and returns the value of the first element that +
The arrFindLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
callbackFn
, its value passed to the callbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined.The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
The last element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
0.8.0
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
function isCherries(fruit) {
return fruit.name === "cherries";
}
console.log(arrFindLast(inventory, isCherries));
// { name: 'cherries', quantity: 5 }
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log(arrFindLast([4, 6, 8, 12], isPrime)); // undefined, not found
console.log(arrFindLast([4, 5, 7, 12], isPrime)); // 7
// Array Like
console.log(arrFindLast({ length: 4, 0: 4, 1: 6, 2: 8, 3: 12 }, isPrime)); // undefined, not found
console.log(arrFindLast({ length: 4, 0: 4, 1: 5, 2: 7, 3: 12 }, isPrime)); // 7
-Generated using TypeDoc
Generated using TypeDoc
The arrFindLastIndex() method iterates the array in reverse order and returns the index of the first element that +
The arrFindLastIndex() method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
The arrFindLastIndex() method is an iterative method. It calls a provided callbackFn
function once for each element
in an array in descending-index order, until callbackFn returns a truthy value. arrFindLastIndex() then returns the
@@ -13,16 +13,16 @@
callbackFn
, its value passed to the callbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined.The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
The index of the last (highest-index) element in the array that passes the test. Otherwise -1 if no matching element is found.
0.8.0
const inventory: Array<{ name: string, quantity: number}> = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 }
];
let called = 0;
function isCherries(fruit: { name: string, quantity: number}) {
called++;
return fruit.name === "cherries";
}
arrFindLastIndex(inventory, isCherries)' // 2
// called === 1
called = 0;
function isPrime(element: number) {
called++;
if (element % 2 === 0 || element < 2) {
return false;
}
for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
if (element % factor === 0) {
return false;
}
}
return true;
}
arrFindLastIndex([4, 6, 8, 9, 12], isPrime); // -1
// called === 5
called = 0;
arrFindLastIndex([4, 6, 7, 9, 12], isPrime); // 2
// called === 3
// Array Like
called = 0;
arrFindLastIndex({ length: 5: 0: 4, 1: 6, 2: 8, 3: 9, 4: 12 }, isPrime); // -1
// called === 5
called = 0;
arrFindLastIndex({ length: 5: 0: 4, 1: 6, 2: 7, 3: 9, 4: 12 }, isPrime); // 2
// called === 3
-Generated using TypeDoc
Generated using TypeDoc
Calls the provided callbackFn
function once for each element in an array in ascending index order. It is not invoked for index properties
+
Calls the provided callbackFn
function once for each element in an array in ascending index order. It is not invoked for index properties
that have been deleted or are uninitialized. And unlike the ES6 forEach() you CAN stop or break the iteration by returning -1 from the
callbackFn
function.
The range (number of elements) processed by arrForEach() is set before the first call to the callbackFn
. Any elements added beyond the range
or elements which as assigned to indexes already processed will not be visited by the callbackFn
.
The array or array like object of elements to be searched.
-A synchronous
function that accepts up to three arguments. arrForEach calls the callbackfn function one time for each element in the array.
Optional
thisArg: anyAn object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined +
The array or array like object of elements to be searched.
+A synchronous
function that accepts up to three arguments. arrForEach calls the callbackfn function one time for each element in the array.
Optional
thisArg: anyAn object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined the array will be used as the this value.
arrForEach expects a synchronous
function.
arrForEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.
const items = ['item1', 'item2', 'item3'];
const copyItems = [];
// before using for loop
for (let i = 0; i < items.length; i++) {
copyItems.push(items[i]);
}
// before using forEach()
items.forEach((item) => {
copyItems.push(item);
});
// after
arrForEach(items, (item) => {
copyItems.push(item);
// May return -1 to abort the iteration
});
// Also supports input as an array like object
const items = { length: 3, 0: 'item1', 1: 'item2', 2: 'item3' };
-Generated using TypeDoc
Generated using TypeDoc
Creates an new shallow-copied array from an array-like object or an iterable.
-Identifies the element type of the array-like or iterable.
-Identifies returned type of the array
-An array-like object or iterable to convert to an array.
-Optional
mapFn: ArrFromMapFn<T, U>Optional
thisArg: anyValue of 'this' used to invoke the mapfn.
+Creates an new shallow-copied array from an array-like object or an iterable.
+Identifies the element type of the array-like or iterable.
+Identifies returned type of the array
+An array-like object or iterable to convert to an array.
+Optional
mapFn: ArrFromMapFn<T, U>Optional
thisArg: anyValue of 'this' used to invoke the mapfn.
0.9.7
arrFrom("Hello");
// [ "H", "e", "l", "l", "o" ]
arrFrom(new Set(["Hello", "Darkness", "my", "old", "friend"]));
// ["Hello", "Darkness", "my", "old", "friend"]
let map = new Map([
[ 1, "Hello" ],
[ 2, "Darkness" ],
[ 3, "my" ],
[ 4, "old" ],
[ 5, "friend"]
]);
arrFrom(map.values());
// ["Hello", "Darkness", "my", "old", "friend"]
arrFrom(map.keys());
// [ 1, 2, 3, 4, 5 ]
arrFrom(map.entries());
// [ [ 1, "Hello" ], [ 2, "Darkness" ], [ 3, "my" ], [ 4, "old" ], [ 5, "friend"] ]
// With a Mapping function
const map = new Map([
[ 1, "Hello" ],
[ 2, "Darkness" ],
[ 3, "my" ],
[ 4, "old" ],
[ 5, "friend"]
]);
arrFrom(map, ([ key, value ]) => ({ [key]: value }));
// [ {"1": "Hello"}, {"2": "Darkness"}, {"3": "my"}, {"4": "old"}, {"5": "friend"} ]
-Generated using TypeDoc
Generated using TypeDoc
The arrIncludes() method determines whether an array includes a certain value among its +
The arrIncludes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
-The array or array like object of elements to be searched.
-The value to search for
-Optional
fromIndex: numberThe optional Zero-based index at which to start searching, converted to an integer.
+The array or array like object of elements to be searched.
+The value to search for
+Optional
fromIndex: numberThe optional Zero-based index at which to start searching, converted to an integer.
0.8.0
arrIncludes([1, 2, 3], 2); // true
arrIncludes([1, 2, 3], 4); // false
arrIncludes([1, 2, 3], 3, 3); // false
arrIncludes([1, 2, 3], 3, -1); // true
arrIncludes([1, 2, NaN], NaN); // true
arrIncludes(["1", "2", "3"], 3 as any); // false
// Array Like
arrIncludes({ length: 3, 0: 1, 1: 2, 2: 3 }, 2); // true
arrIncludes({ length: 3, 0: 1, 1: 2, 2: 3 }, 4); // false
arrIncludes({ length: 3, 0: 1, 1: 2, 2: 3 }, 3, 3); // false
arrIncludes({ length: 3, 0: 1, 1: 2, 2: 3 }, 3, -1); // true
arrIncludes({ length: 3, 0: 1, 1: 2, 2: NaN }, NaN); // true
arrIncludes({ length: 3, 0: "1", 1: "2", 2: "3" }, 3 as any); // false
-Generated using TypeDoc
Generated using TypeDoc
The arrIndexOf() method returns the first index at which a given element can be found in the array, +
The arrIndexOf() method returns the first index at which a given element can be found in the array,
or -1 if it is not present.
arrIndexOf()
compares searchElement to elements of the Array using strict equality (the same
method used by the === or triple-equals operator).
The array or array like object of elements to be searched.
-The element to locate in the array.
-Optional
fromIndex: numberThe index to start the search at. If the index is greater than or equal to +
The array or array like object of elements to be searched.
+The element to locate in the array.
+Optional
fromIndex: numberThe index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the @@ -13,4 +13,4 @@
The first index of the element in the array; -1 if not found.
const array = [2, 9, 9];
arrIndexOf(array, 2); // 0
arrIndexOf(array, 7); // -1
arrIndexOf(array, 9, 2); // 2
arrIndexOf(array, 2, -1); // -1
arrIndexOf(array, 2, -3); // 0
let indices: number[] = [];
const array = ['a', 'b', 'a', 'c', 'a', 'd'];
const element = 'a';
let idx = arrIndexOf(array, element);
while (idx !== -1) {
indices.push(idx);
idx = arrIndexOf(array, element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
function updateVegetablesCollection (veggies, veggie) {
if (arrIndexOf(veggies, veggie) === -1) {
veggies.push(veggie);
console.log('New veggies collection is : ' + veggies);
} else {
console.log(veggie + ' already exists in the veggies collection.');
}
}
let veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
updateVegetablesCollection(veggies, 'spinach');
// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, 'spinach');
// spinach already exists in the veggies collection.
// Array Like
let arrayLike = {
length: 3,
0: "potato",
1: "tomato",
2: "chillies",
3: "green-pepper" // Not checked as index is > length
};
arrIndexOf(arrayLike, "potato"); // 0
arrIndexOf(arrayLike, "tomato"); // 1
arrIndexOf(arrayLike, "chillies"); 2
arrIndexOf(arrayLike, "green-pepper"); // -1
-Generated using TypeDoc
Generated using TypeDoc
The arrLastIndexOf() method returns the last index at which a given element can be found in the array, +
The arrLastIndexOf() method returns the last index at which a given element can be found in the array,
or -1 if it is not present.
arrLastIndexOf()
compares searchElement to elements of the Array using strict equality (the same
method used by the === or triple-equals operator). NaN
values are never compared as equal, so arrLastIndexOf() always returns -1 when searchElement is NaN.
The arrLastIndexOf() method skips empty slots in sparse arrays.
The arrLastIndexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.
-The array or array like object of elements to be searched.
-The element to locate in the array.
-Optional
fromIndex: numberZero-based index at which to start searching backwards, converted to an integer.
+The array or array like object of elements to be searched.
+The element to locate in the array.
+Optional
fromIndex: numberZero-based index at which to start searching backwards, converted to an integer.
0.8.0
const numbers = [2, 5, 9, 2];
arrLastIndexOf(numbers, 2); // 3
arrLastIndexOf(numbers, 7); // -1
arrLastIndexOf(numbers, 2, 3); // 3
arrLastIndexOf(numbers, 2, 2); // 0
arrLastIndexOf(numbers, 2, -2); // 0
arrLastIndexOf(numbers, 2, -1); // 3
let indices: number[] = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = arrLastIndexOf(array, element);
while (idx !== -1) {
indices.push(idx);
idx = arrLastIndexOf(array, element, idx ? idx - 1 : -(array.length + 1));
}
console.log(indices);
// [4, 2, 0]
function updateVegetablesCollection (veggies, veggie) {
if (arrLastIndexOf(veggies, veggie) === -1) {
veggies.push(veggie);
console.log('New veggies collection is : ' + veggies);
} else {
console.log(veggie + ' already exists in the veggies collection.');
}
}
let veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
updateVegetablesCollection(veggies, 'spinach');
// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, 'spinach');
// spinach already exists in the veggies collection.
// Array Like
let arrayLike = {
length: 3,
0: "potato",
1: "tomato",
2: "chillies",
3: "green-pepper" // Not checked as index is > length
};
arrLastIndexOf(arrayLike, "potato"); // 0
arrLastIndexOf(arrayLike, "tomato"); // 1
arrLastIndexOf(arrayLike, "chillies"); 2
arrLastIndexOf(arrayLike, "green-pepper"); // -1
-Generated using TypeDoc
Generated using TypeDoc
The arrMap() method creates a new array populated with the results of calling a provided function on every +
The arrMap() method creates a new array populated with the results of calling a provided function on every element in the calling array.
arrMap
calls a provided callbackFn function once for each element in an array, in order, and constructs
a new array from the results. callbackFn is invoked only for indexes of the array which have assigned
@@ -8,12 +8,12 @@
Identifies the type of the array elements
-Identifies the type of the elements returned by the callback function, defaults to T.
-The array or array like object of elements to be searched.
-The function that is called for evetn element of theArray
.
Optional
thisArg: anyThe value to use as the this
when executing the callbackFn
.
Identifies the type of the array elements
+Identifies the type of the elements returned by the callback function, defaults to T.
+The array or array like object of elements to be searched.
+The function that is called for evetn element of theArray
.
Optional
thisArg: anyThe value to use as the this
when executing the callbackFn
.
0.3.3
const numbers = [1, 4, 9];
const roots = arrMap(numbers, (num) => Math.sqrt(num));
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
const kvArray = [{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 }];
const reformattedArray = arrMap(kvArray, ({ key, value}) => ({ [key]: value }));
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],
// kvArray is still:
// [{key: 1, value: 10},
// {key: 2, value: 20},
// {key: 3, value: 30}]
// Also supports Array Like objects with same output
const kvArray = {
length: 3,
0: { key: 1, value: 10 },
1: { key: 2, value: 20 },
2: { key: 3, value: 30 }
};
-Generated using TypeDoc
Generated using TypeDoc
The arrReduce() method executes a user-supplied "reducer" callback function on each element of the array, +
The arrReduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
-Identifies the type of array elements
-The array or array like object of elements to be searched.
-A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
-Optional
initialValue: T | RIf initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
+Identifies the type of array elements
+The array or array like object of elements to be searched.
+A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
+Optional
initialValue: T | RIf initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
The value that results from running the "reducer" callback function to completion over the entire array.
const getMax = (a: number, b: number) => Math.max(a, b);
// callback is invoked for each element in the array starting at index 0
arrReduce([1, 100], getMax, 50); // 100
arrReduce([ 50], getMax, 10); // 50
// callback is invoked once for element at index 1
arrReduce([1, 100], getMax); // 100
// callback is not invoked
arrReduce([ 50], getMax); // 50
arrReduce([ ], getMax, 1); // 1
arrReduce([ ], getMax); // throws TypeError
// Also supports Array like objects
arrReduce({ length: 2, 0: 1, 1: 100 }, getMax, 50); // 100
arrReduce({ length: 1, 0: 50 }, getMax, 10); // 50
// callback is invoked once for element at index 1
arrReduce({ length: 2, 0: 1, 1: 100 }, getMax); // 100
// callback is not invoked
arrReduce({ length: 1, 0: 50 }, getMax); // 50
arrReduce({ length: 0 }, getMax, 1); // 1
* ```
-Generated using TypeDoc
Generated using TypeDoc
The arrSlice() method returns a shallow copy of a portion of an array into a new array object +
The arrSlice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
The arrSlice()
method is a copying method. It does not alter this but instead returns a shallow
@@ -9,13 +9,13 @@
integer-keyed properties.
For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.
-Optional
start: numberZero-based index at which to start extraction, converted to an integer.
+Optional
start: numberZero-based index at which to start extraction, converted to an integer.
Optional
end: numberZero-based index at which to end extraction, converted to an integer. slice() extracts +
Optional
end: numberZero-based index at which to end extraction, converted to an integer. slice() extracts up to but not including end.
0.9.3
const lyrics = ["Hello", "Darkness", "my", "old", "friend.", "I've", "come", "to", "talk" ];
arrSlice(lyrics); // [ "Hello", "Darkness", "my", "old", "friend.", "I've", "come", "to", "talk" ]
arrSlice(lyrics, 1, 3); // [ "Darkness", "my" ]
arrSlicw(lyrics, 2); // [ "my", "old", "friend.", "I've", "come", "to", "talk" ]
arrSlice(lyrics, 2, 4); // [ "my", "old" ]
arrSlice(lyrics, 1, 5); // [ "Darkness", "my", "old", "friend." ]
arrSlice(lyrics, -2); // [ "to", "talk" ]
arrSlice(lyrics, 2, -1); // [ "my", "old", "friend.", "I've", "come", "to" ]
-Generated using TypeDoc
Generated using TypeDoc
The arrSome() method tests whether at least one element in the array passes the test implemented by the +
The arrSome() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
The arrSome() method is an iterative method. It calls a provided callbackFn
function once for each element
@@ -18,14 +18,14 @@
callbackFn
will be the value at the time that element gets visited. Deleted elements are not visited.
The array or array like object of elements to be searched.
-A function that accepts up to three arguments of type ArrPredicateCallbackFn or +
The array or array like object of elements to be searched.
+A function that accepts up to three arguments of type ArrPredicateCallbackFn or ArrPredicateCallbackFn2. The predicate function is called for each element in the thArray until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
-Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
+Optional
thisArg: anyA value to use as this when executing callbackFn. Defaults to the array if not provided.
true
if the callback function returns a truthy value for at least one element in the array.
Otherwise, false
.
0.8.0
-Generated using TypeDoc
Generated using TypeDoc
Deep copy handler to identify and copy arrays.
-The details object for the current property being copied
+Deep copy handler to identify and copy arrays.
+The details object for the current property being copied
true
if the current value is a function otherwise false
0.4.4
-Generated using TypeDoc
Generated using TypeDoc
The asString() method returns a string representing the value by +
The asString() method returns a string representing the value by
explicitly using String(
value)
.
The value to get a string representation of
+The value to get a string representation of
0.4.3
const arr = [ 1, 2, 3];
asString(arr); // "1,2,3"
asString(null); // "null"
asString(undefined); // "undefined"
asString(42); // "42"
asString(Symbol.for("Hello")); // "Symbol(Hello)"
-Generated using TypeDoc
Generated using TypeDoc
Create an iterator which is backed by the provided array, unlike a normal +
Create an iterator which is backed by the provided array, unlike a normal
array iterators where the array cannot be modified function creates
a shallow copy of the array using slice()
so that you are free to modify
the original array.
This will still return an iterator if the provided values
is null or
undefined which will result in no entries.
The source array to create an iterator from
+The source array to create an iterator from
A new iterator
0.4.2
let cnt = 0;
let values = [];
iterForOf(createArrayIterator([10, 20, 5, 15]), (value) => {
cnt++;
values.push(value);
});
-Generated using TypeDoc
Generated using TypeDoc
Create and return a readonly ICachedValue instance that is populated with the provided value. +
Create and return a readonly ICachedValue instance that is populated with the provided value. This is useful when you want to cache a previously fetched value and return it without having to re-fetch it again. This is a lightweight version of getLazy which does not support any expiration or invalidation, it also will not honor the setBypassLazyCache setting and will always return the provided value.
-A new ICachedValue instance which wraps the provided value
+A new ICachedValue instance which wraps the provided value
0.10.5
T - The type of the value to be cached
let cachedValue = createCachedValue("some value");
// cachedValue.v === "some value"
JSON.stringify(cachedValue) === '{"v":"some value"}';
-Generated using TypeDoc
Generated using TypeDoc
Create a Custom Error class which may be used to throw custom errors.
-The name of the Custom Error
-Optional
constructCb: ((self, args) => void)[Optional] An optional callback function to call when a +
Create a Custom Error class which may be used to throw custom errors.
+The name of the Custom Error
+Optional
constructCb: ((self, args) => void)[Optional] An optional callback function to call when a new Customer Error instance is being created.
-Optional
errorBase: B[Optional] (since v0.9.6) The error class to extend for this class, defaults to Error.
+Optional
errorBase: B[Optional] (since v0.9.6) The error class to extend for this class, defaults to Error.
A new Error class
import { createCustomError, isError } from "@nevware21/ts-utils";
// For an error that just contains a message
let myCustomErrorError = createCustomError("MessageError");
try {
throw new myCustomErrorError("Error Message!");
} catch(e) {
// e.name === MessageError
// isError(e) === true;
// Object.prototype.toString.call(e) === "[object Error]";
}
// Or a more complex error object
interface MyCriticalErrorConstructor extends CustomErrorConstructor {
new(message: string, file: string, line: number, col: number): MyCriticalError;
(message: string, file: string, line: number, col: number): MyCriticalError;
}
interface MyCriticalError extends Error {
readonly errorId: number;
readonly args: any[]; // Holds all of the arguments passed during construction
}
let _totalErrors = 0;
let myCustomError = createCustomError<MyCriticalErrorConstructor>("CriticalError", (self, args) => {
_totalErrors++;
self.errorId = _totalErrors;
self.args = args;
});
try {
throw new myCustomError("Not Again!");
} catch(e) {
// e.name === CriticalError
// isError(e) === true;
// Object.prototype.toString.call(e) === "[object Error]";
}
// ----------------------------------------------------------
// Extending another custom error class
// ----------------------------------------------------------
let AppError = createCustomError("ApplicationError");
let theAppError = new appError();
isError(theAppError); // true
theAppError instanceof Error; // true
theAppError instanceof AppError; // true
let StartupError = createCustomError("StartupError", null, AppError);
let theStartupError = new StartupError();
isError(theStartupError); // true
theStartupError instanceof Error; // true
theStartupError instanceof AppError; // true
theStartupError instanceof StartupError; // true
-Generated using TypeDoc
Generated using TypeDoc
Create and return a readonly ICachedValue instance which will cache and return the value returned +
Create and return a readonly ICachedValue instance which will cache and return the value returned by the callback function. The callback function will only be called once, multiple access of the value will not cause re-execution of the callback as the result from the first call is cached internally. This is a lightweight version of getLazy which does not support any expiration or invalidation, it also will not honor the setBypassLazyCache setting and will always return the provided value.
-The callback function to fetch the value to be lazily evaluated and cached
+0.10.5
T - The type of the value to be cached
-Generated using TypeDoc
Generated using TypeDoc
Create a TypeScript style enum class which is a mapping that maps from the key -> value and the value -> key. +
Create a TypeScript style enum class which is a mapping that maps from the key -> value and the value -> key. This is effectively the same as defining a non-constant enum, but this only repeats the "Name" of the enum value once.
-The values to populate on the new object
+A new frozen (immutable) object which looks and acts like a TypeScript Enum class.
const enum Animal {
Dog = 0,
Cat = 1,
Butterfly = 2,
Bear = 3
}
const Animals = createEnum<typeof Animal>({
Dog: Animal.Dog,
Cat: Animal.Cat,
Butterfly: Animal.Butterfly,
Bear: Animal.Bear
});
// You end up with an object that maps everything to the name
Animals.Dog === 0; // true
Animals[0] === "Dog"; // true
Animals["Dog"] === 0; // true
Animals.Cat === 1; // true
Animals[1] === "Cat"; // true
Animals["Cat"] === 1; // true
-Generated using TypeDoc
Generated using TypeDoc
Create a map object which contains both the property key and value which both map to the key, +
Create a map object which contains both the property key and value which both map to the key, E[key] => key and E[value] => key.
-The values to populate on the new object
+A new frozen (immutable) object which contains a property for each key and value that returns the value.
const enum Animal {
Dog = 0,
Cat = 1,
Butterfly = 2,
Bear = 3
}
const animalMap = createEnumKeyMap<typeof Animal>({
Dog: Animal.Dog,
Cat: Animal.Cat,
Butterfly: Animal.Butterfly,
Bear: Animal.Bear
});
// You end up with an object that maps everything to the name
animalMap.Dog === "Dog"; // true
animalMap[0] === "Dog"; // true
animalMap["Dog"] === "Dog"; // true
animalMap.Cat === "Cat"; // true
animalMap[1] === "Cat"; // true
animalMap["Cat"] === "Cat"; // true
// Helper function to always return the "Name" of the type of animal
function getAnimalType(type: string | number | Animal) {
return animalMap[type];
}
-Generated using TypeDoc
Generated using TypeDoc
Create a map object which contains both the perperty key and value which both map to the resulting value, +
Create a map object which contains both the perperty key and value which both map to the resulting value, E[key] => value and E[value] => value.
-The values to populate on the new object
+A new frozen (immutable) object which contains a property for each key and value that returns the value.
const enum Animal {
Dog = 0,
Cat = 1,
Butterfly = 2,
Bear = 3
}
const animalMap = createEnumValueMap<typeof Animal>({
Dog: Animal.Dog,
Cat: Animal.Cat,
Butterfly: Animal.Butterfly,
Bear: Animal.Bear
});
// You end up with an object that maps everything to the name
animalMap.Dog === 0; // true
animalMap[0] === 0; // true
animalMap["Dog"] === 0; // true
animalMap.Cat === 1; // true
animalMap[1] === 1; // true
animalMap["Cat"] === 1; // true
// Helper function to always return the "Name" of the type of animal
function getAnimalValue(type: string | number | Animal) {
return animalMap[type];
}
-Generated using TypeDoc
Generated using TypeDoc
Create a simple filename style regular expression from the string value, converting any embedded +
Create a simple filename style regular expression from the string value, converting any embedded
filename wildcard characters '*'
and '?'
.
If the source string contains folder seperators both '/'
and '\'
are treated as synonomous.
Each wildcard match will be captured as it's own group.
@@ -9,13 +9,13 @@
'/'
Matches either '/'
or '\'
character, not captured as a group'\'
Matches either '/'
or '\'
character, not captured as a groupThe string value to converted
-Optional
ignoreCase: booleanFlag to indicate whether the regular expression should be case-sensitive, Defaults +
The string value to converted
+Optional
ignoreCase: booleanFlag to indicate whether the regular expression should be case-sensitive, Defaults to false.
-Optional
fullMatch: booleanFlag to identify whether the RegExp should be wrapped with '^'
and '$'
to
+
Optional
fullMatch: booleanFlag to identify whether the RegExp should be wrapped with '^'
and '$'
to
incidate match the entire string only.
The new Regular Expression created from the provided value.
0.9.0
let regex = createFilenameRegex("*.txt");
lat matches = regex.exec("Hello");
matches; // null
let matches = regex.exec("ug.txt");
matches[0]; // "ug.txt"
matches[1]; // "ug"
let matches = regex.exec(" ug.txt ");
matches[0]; // " ug.txt"
matches[1]; // " ug"
let matches = regex.exec("C:\\temp\\ug.txt");
matches[0]; // "C:\\temp\\ug.txt"
matches[1]; // "C:\\temp\\ug"
let matches = regex.exec("/var/log/ug.txt");
matches[0]; // "/var/log/ug.txt"
matches[1]; // "/var/log/ug"
-Generated using TypeDoc
Generated using TypeDoc
Create a deferred proxy function which will call the named function of the result of the hostFn, this enables +
Create a deferred proxy function which will call the named function of the result of the hostFn, this enables creating bound functions which when called call the proxy the function to a different host (this) instance.
This is different from fnBind
which is provided with the concrete function and this
instances, while the proxy
will lazily obtain the this
and the function is obtained by looking up the named function from the returned
host (this
) instance.
A function to get the current host and thisArg that will be called
-The name of the function to call on the host
+A function to get the current host and thisArg that will be called
+The name of the function to call on the host
The result of calling the function with the specified this
value and arguments.
0.9.8
const module1 = {
prefix: "Hello",
x: 21,
getX() {
return this.x;
},
log(value: string) {
return this.prefix + " " + value + " : " + this.x
}
};
// The 'this' parameter of 'getX' is bound to 'module'.
module1.getX(); // 21
module1.log("Darkness"); // Hello Darkness : 21
// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
let module2 = {
prefix: "my",
x: 42
};
let getHost = () => {
return module1;
};
let deferredFn = createFnDeferredProxy(getHost, "getX");
deferredFn(); // 21
module2.defX = deferredFn;
module2.defX(); // 21
-Generated using TypeDoc
Generated using TypeDoc
Create an iterable which conforms to the Iterable
protocol, it uses the provided ctx
to
+
Create an iterable which conforms to the Iterable
protocol, it uses the provided ctx
to
create an Iterator
via createIterator.
The context used to manage the iteration over the items.
+The context used to manage the iteration over the items.
A new Iterable instance
0.4.2
let current = 0;
let next = 1;
let done = false;
let fibCtx: CreateIteratorContext<number> = {
n: function() {
fibCtx.v = current;
current = next;
next = fibCtx.v + next;
// Return not done
return false;
},
r: function(value) {
done = true;
return value;
}
};
let values: number[] = [];
iterForOf(createIterable(fibCtx), (value) => {
values.push(value);
if (values.length === 10) {
return -1;
}
});
// Done is true
// done === true
// Values: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
-Generated using TypeDoc
Generated using TypeDoc
Create an iterator which conforms to the Iterator
protocol, it uses the provided ctx
to
+
Create an iterator which conforms to the Iterator
protocol, it uses the provided ctx
to
managed moving to the next
.
The context used to manage the iteration over the items.
+The context used to manage the iteration over the items.
A new Iterator instance
0.4.2
let idx = -1;
let theValues = [ 5, 10, 15, 20, 25, 30 ];
function getNextFn() {
idx++;
let isDone = idx >= theValues.length;
if (!isDone) {
// this is passed as the current iterator
// so you can directly assign the next "value" that will be returned
this.v = theValues[idx];
}
return isDone;
}
let theIterator = createIterator<number>({ n: getNextFn });
let values: number[] = [];
iterForOf(theIterator, (value) => {
values.push(value);
});
// Values: [5, 10, 15, 20, 25, 30 ]
-Generated using TypeDoc
Generated using TypeDoc
Creates proxy functions on the target which internally will call the source version with all arguments passed to the target method.
-The target object to be assigned with the source properties and functions
-The host instance or a function to return the host instance which contains the +
Creates proxy functions on the target which internally will call the source version with all arguments passed to the target method.
+The target object to be assigned with the source properties and functions
+The host instance or a function to return the host instance which contains the
functions and will be assigned as the this
for the function being called.
An array of function definitions on how each named function will be +
An array of function definitions on how each named function will be proxied onto the target.
The original target after all proxies have been assigned
0.9.8
let test = {
x: 21,
func1() {
return this.x;
}
};
test.func1(); // 21
let newTarget = createProxyFuncs({} as any, test, [
{ n: "func1" },
{ n: "func1", as: "aliasFn" }
]);
newTarget.func1(); // 21
newTarget.aliasFn(); // 21
newTarget.x = 42;
// The return is still using the `this.x` from the original `test` as it's proxied
newTarget.func1(); // 21
newTarget.aliasFn(); // 21
let getHostFn = () => {
return test;
};
newTarget = createProxyFuncs({} as any, getHostFn, [
{ n: "func1" },
{ n: "func1", as: "aliasFn" }
]);
newTarget.func1(); // 21
newTarget.aliasFn(); // 21
newTarget.x = 42;
// The return is still using the `this.x` from the original `test` as it's proxied
newTarget.func1(); // 21
newTarget.aliasFn(); // 21
-Generated using TypeDoc
Generated using TypeDoc
Create a simple range iterator which will return an iterator that increments it's value from +
Create a simple range iterator which will return an iterator that increments it's value from
start
to end
by the step
.
end
is omitted, null or undefined the value will be set to start
step
value is omitted, null, undefined or zero then it will default to 1 if end > start otherwise -1.The initial value of the numeric iterator
-The inclusive maximum (or minimum when moving backwards) value of the iterator.
-Optional
step: numberThe step size for each iteration, may be positive or negative. Defaults to 1 when +
The initial value of the numeric iterator
+The inclusive maximum (or minimum when moving backwards) value of the iterator.
+Optional
step: numberThe step size for each iteration, may be positive or negative. Defaults to 1 when start <= end and -1 when start > end. Zero is treated as not provided.
A new iterator which will return a numeric value between start and end at step intervals
0.4.2
let cnt = 0;
iterForOf(createRangeIterator(0, -1, 1), (value) => {
// Will never get called as -1 < 0
});
cnt = 0;
let values: number[] = [];
iterForOf(createRangeIterator(1, 1), (value) => {
cnt++;
values.push(value);
});
// cnt === 1
// values: [ 1 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(10, null as any), (value) => {
cnt++;
values.push(value);
});
// cnt === 1
// values: [ 10 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(-10, undefined as any), (value) => {
cnt++;
values.push(value);
});
// cnt === 1
// values: [ -10 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(5, 20, 5), (value) => {
cnt++;
values.push(value);
});
// cnt === 4
// values: [ 5, 10, 15, 20 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(20, 5, -5), (value) => {
cnt++;
values.push(value);
});
// cnt === 4
// values: [ 20, 15, 10, 5 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(20, 15), (value) => {
cnt++;
values.push(value);
});
// cnt === 6
// values: [ 20, 19, 18, 17, 16, 15 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(-1, 1), (value) => {
cnt++;
values.push(value);
});
// cnt === 3;
// values: [ -1, 0, 1 ]
cnt = 0;
values = [];
iterForOf(createRangeIterator(1, -1), (value) => {
cnt++;
values.push(value);
});
// cnt === 3;
// values: [ 1, 0, -1 ]
-Generated using TypeDoc
Generated using TypeDoc
Create a map object which contains both the perperty key and value which both map to the requested +
Create a map object which contains both the perperty key and value which both map to the requested generic mapValue with a type of V, E[key] => mapValue and E[value] => mapValue.
-The values to populate on the new object
+A new frozen (immutable) object which contains a property for each key and value that returns the defiend mapped value.
const enum Animal {
Dog = 0,
Cat = 1,
Butterfly = 2,
Bear = 3
};
// Creates a simple mapping to a string value
const animalFamilyMap = createValueMap<typeof Animal, string>({
Dog: [ Animal.Dog, "Canidae"],
Cat: [ Animal.Cat, "Felidae"],
Butterfly: [ Animal.Butterfly, "Papilionidae"],
Bear: [ Animal.Bear, "Ursidae"]
});
// You end up with an object that maps everything to the name
animalMap.Dog === "Canidae"; // true with typeof animalMap.Dog is "string"
animalMap[0] === "Canidae"; // true with typeof animalMap[0] is "string"
animalMap["Dog"] === "Canidae"; // true with typeof animalMap["Dog"] is "string"
animalMap.Cat === "Felidae"; // true with typeof animalMap.Cat is "string"
animalMap[1] === "Felidae"; // true with typeof animalMap[1] is "string"
animalMap["Cat"] === "Felidae"; // true with typeof animalMap["Cat"] is "string"
-Generated using TypeDoc
Generated using TypeDoc
Creates a non-running (paused) timer which will execute a function or specified piece of code when enabled and the timer expires, +
Creates a non-running (paused) timer which will execute a function or specified piece of code when enabled and the timer expires,
this is simular to using scheduleTimeout
but the timer is not enabled (running) and you MUST call refresh
to start the timer.
The timer may be cancelled (cleared) by calling the cancel()
function on the returned ITimerHandler, or
you can "reschedule" and/or "restart" the timer by calling the refresh()
function on the returned ITimerHandler
instance
The function to be executed after the timer expires.
-Rest
...args: AThe time, in milliseconds that the timer should wait before the specified +
The function to be executed after the timer expires.
+Rest
...args: AThe time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle.
-Rest
...args: AAdditional arguments which are passed through to the function specified by callback
.
Rest
...args: AAdditional arguments which are passed through to the function specified by callback
.
A ITimerHandler instance which can be used to cancel the timeout.
0.7.0
let timeoutCalled = false;
let theTimeout = createTimeout(() => {
// This callback will be called after 100ms as this uses setTimeout()
timeoutCalled = true;
}, 100);
// As the timer is not started you will need to call "refresh" to start the timer
theTimeout.refresh();
// or set enabled to true
theTimeout.enabled = true;
-Generated using TypeDoc
Generated using TypeDoc
Creates a non-running (paused) timer which will execute a function or specified piece of code when enabled once the timer expires. +
Creates a non-running (paused) timer which will execute a function or specified piece of code when enabled once the timer expires.
The overrideFn will be used to create the timer, this is simular to using scheduleTimeoutWith
but the timer is not enabled (running)
and you MUST call refresh
to start the timer.
The timer may be cancelled (cleared) by calling the cancel()
function on the returned ITimerHandler, or
you can "reschedule" and/or "restart" the timer by calling the refresh()
function on the returned ITimerHandler
instance
setTimeout override function this will be called instead of the setTimeout
, if the value
+
setTimeout override function this will be called instead of the setTimeout
, if the value
of overrideFn
is null or undefined it will revert back to the native setTimeout
. May also be an array with contains
both the setTimeout and clearTimeout override functions, if either is not provided the default native functions will be used
The function to be executed after the timer expires.
-Rest
...args: AThe time, in milliseconds that the timer should wait before the specified +
The function to be executed after the timer expires.
+Rest
...args: AThe time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle.
-Rest
...args: AAdditional arguments which are passed through to the function specified by callback
.
Rest
...args: AAdditional arguments which are passed through to the function specified by callback
.
A ITimerHandler instance which can be used to cancel the timeout.
0.7.0
let timeoutCalled = false;
// Your own "setTimeout" implementation to allow you to perform additional operations or possible wrap
// the callback to add timings.
function newSetTimeoutFn(callback: TimeoutOverrideFn) {
overrideCalled ++;
return setTimeout(callback, timeout);
}
let theTimeout = createTimeoutWith(newSetTimeoutFn, () => {
// This callback will be called after 100ms as this uses setTimeout()
timeoutCalled = true;
}, 100);
// As the timer is not started you will need to call "refresh" to start the timer
theTimeout.refresh();
// or set enabled to true
theTimeout.enabled = true;
let timeoutCalled = false;
// Your own "setTimeout" implementation to allow you to perform additional operations or possible wrap
// the callback to add timings.
function newSetTimeoutFn(callback: TimeoutOverrideFn) {
overrideCalled ++;
return setTimeout(callback, timeout);
}
// Your own "clearTimeout" implementation to allow you to perform additional operations or possible wrap
// the callback to add timings.
function newClearTimeoutFn(timeoutId: number) {
overrideCalled ++;
return clearTimeout( timeout);
}
let theTimeout = createTimeoutWith([newSetTimeoutFn, newClearTimeoutFn], () => {
// This callback will be called after 100ms as this uses setTimeout()
timeoutCalled = true;
}, 100);
// As the timer is not started you will need to call "refresh" to start the timer
theTimeout.refresh();
// or set enabled to true
theTimeout.enabled = true;
-Generated using TypeDoc
Generated using TypeDoc
Create a strongly types map object which contains both the perperty key and value which both map +
Create a strongly types map object which contains both the perperty key and value which both map to the requested mapValue, E[key] => mapValue and E[value] => mapValue.
The values to populate on the new object
+A new frozen (immutable) object which contains a property for each key and value that returns the defined mapped value.
// Create a strongly types map
const animalFamilyMap = createTypeMap<typeof Animal, {
// Defined the enum lookups
[Animal.Dog]: "Canidae",
[Animal.Cat]: "Felidae",
[Animal.Butterfly]: "Papilionidae",
[Animal.Bear]: "Ursidae",
// Defined Named reference
Dog: "Canidae",
Cat: "Felidae",
Butterfly: "Papilionidae",
Bear: "Ursidae",
}>({
Dog: [ Animal.Dog, "Canidae"],
Cat: [ Animal.Cat, "Felidae"],
Butterfly: [ Animal.Butterfly, "Papilionidae"],
Bear: [ Animal.Bear, "Ursidae"]
});
// You end up with a strongly types result for each value
animalMap.Dog === "Canidae"; // true with typeof animalMap.Dog is (const) "Canidae"
animalMap[0] === "Canidae"; // true with typeof animalMap[0] is "Canidae"
animalMap["Dog"] === "Canidae"; // true with typeof animalMap["Dog"] is "Canidae"
animalMap.Cat === "Felidae"; // true with typeof animalMap.Cat is "Felidae"
animalMap[1] === "Felidae"; // true with typeof animalMap[1] is "Felidae"
animalMap["Cat"] === "Felidae"; // true with typeof animalMap["Cat"] is "Felidae"
or using an interface to define the direct string mappings
interface IAnimalFamilyMap {
Dog: "Canidae",
Cat: "Felidae",
Butterfly: "Papilionidae",
Bear: "Ursidae"
}
// Create a strongly types map
const animalFamilyMap = createTypeMap<typeof Animal, IAnimalFamilyMap & {
// Defined the enum lookups
[Animal.Dog]: "Canidae",
[Animal.Cat]: "Felidae",
[Animal.Butterfly]: "Papilionidae",
[Animal.Bear]: "Ursidae"
}>({
Dog: [ Animal.Dog, "Canidae"],
Cat: [ Animal.Cat, "Felidae"],
Butterfly: [ Animal.Butterfly, "Papilionidae"],
Bear: [ Animal.Bear, "Ursidae"]
});
// You also end up with a strongly types result for each value
animalMap.Dog === "Canidae"; // true with typeof animalMap.Dog is (const) "Canidae"
animalMap[0] === "Canidae"; // true with typeof animalMap[0] is "Canidae"
animalMap["Dog"] === "Canidae"; // true with typeof animalMap["Dog"] is "Canidae"
animalMap.Cat === "Felidae"; // true with typeof animalMap.Cat is "Felidae"
animalMap[1] === "Felidae"; // true with typeof animalMap[1] is "Felidae"
animalMap["Cat"] === "Felidae"; // true with typeof animalMap["Cat"] is "Felidae"
-Generated using TypeDoc
Generated using TypeDoc
Create a simple wildcard regular expression from the string value, converting any embedded wildcard +
Create a simple wildcard regular expression from the string value, converting any embedded wildcard
'*'
characters to match any character zero or more times (including folder seperators '/'
or '\'
),
while escaping all other characters.
The supported matching values are
'*'
Matches any characters zero or more times (including folder seperators ''/
' or '\'
)The value to be converted into a RegExp, if the value is not a string it will coerced +
The value to be converted into a RegExp, if the value is not a string it will coerced to a string.
-Optional
ignoreCase: booleanFlag to indicate whether the regular expression should be case-sensitive, Defaults +
Optional
ignoreCase: booleanFlag to indicate whether the regular expression should be case-sensitive, Defaults to false.
-Optional
fullMatch: booleanFlag to identify whether the RegExp should be wrapped with '^'
and '$'
to
+
Optional
fullMatch: booleanFlag to identify whether the RegExp should be wrapped with '^'
and '$'
to
incidate match the entire string only.
The new Regular Expression created from the provided value.
0.9.0
let regex = createWildcardRegex("Hello*");
let matches = regex.exec("Hello");
matches[0]; // "Hello";
matches[1]; // ""
let matches = regex.exec("Hello Darkness");
matches[0]; // "Hello Darkness"
matches[1]; // " Darkness"
let matches = regex.exec("Darkness Hello");
matches[0]; // "Hello"
matches[1]; // ""
let regex.exec("Darkness Hello.");
matches[0]; // "Hello."
matches[1]; // "."
-Generated using TypeDoc
Generated using TypeDoc
Deep copy handler to identify and copy Date instances.
-The details object for the current property being copied
+Deep copy handler to identify and copy Date instances.
+The details object for the current property being copied
true
if the current value is a function otherwise false
0.4.4
-Generated using TypeDoc
Generated using TypeDoc
Create a new object by merging the passed arguments, this is effectively the same as calling objExtend({}, ...theArgs)
where
+
Generated using TypeDoc
Generated using TypeDoc
Returns string representation of an object suitable for diagnostics logging.
-The object to be converted to a diagnostic string value
-Optional
format: number | booleanIdentifies whether the JSON value should be formated
+Returns string representation of an object suitable for diagnostics logging.
+The object to be converted to a diagnostic string value
+Optional
format: number | booleanIdentifies whether the JSON value should be formated
true
- Format with 4 spaceslet obj = { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } };
let objStr = dumpObj(obj);
// objStr === "[object Object]: { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } }"
let objStrFmt = dumpObj(obj, true);
// objStrFmt === "[object Object]: {\n a: 1,\n b: "Hello",\n c: {\n d: 2,\n e: "Darkness"\n }\n}"
let objStrFmt2 = dumpObj(obj, 2);
// objStrFmt2 === "[object Object]: {\n a: 1,\n b: "Hello",\n c: {\n d: 2,\n e: "Darkness"\n }\n}"
let objStrFmt3 = dumpObj(obj, 0);
// objStrFmt3 === "[object Object]: { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } }"
let objStrFmt4 = dumpObj(obj, false);
// objStrFmt4 === "[object Object]: { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } }"
let objStrFmt5 = dumpObj(obj, null);
// objStrFmt5 === "[object Object]: { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } }"
let objStrFmt6 = dumpObj(obj, undefined);
// objStrFmt6 === "[object Object]: { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } }"
let objStrFmt7 = dumpObj(obj, "");
// objStrFmt7 === "[object Object]: { a: 1, b: "Hello", c: { d: 2, e: "Darkness" } }"
let err = new Error("Hello Darkness");
let errStr = dumpObj(err);
// errStr === "[object Error]: { stack: 'Error: Hello Darkness\n at <anonymous>:1:13', message: 'Hello Darkness', name: 'Error'"
let errStrFmt = dumpObj(err, true);
// errStrFmt === "[object Error]: {\n stack: "Error: Hello Darkness\n at <anonymous>:1:13",\n message: "Hello Darkness",\n name: "Error"\n}"
let errStrFmt2 = dumpObj(err, 2);
// errStrFmt2 === "[object Error]: {\n stack: "Error: Hello Darkness\n at <anonymous>:1:13",\n message: "Hello Darkness",\n name: "Error"\n}"
let errStrFmt3 = dumpObj(err, 0);
// errStrFmt3 === "[object Error]: { stack: "Error: Hello Darkness\n at <anonymous>:1:13", message: "Hello Darkness", name: "Error" }"
Generated using TypeDoc
Generated using TypeDoc
Return the number of milliseconds that have elapsed since the provided startTime
+
Return the number of milliseconds that have elapsed since the provided startTime
the startTime
MUST be obtained from perfNow to ensure the correct elapsed
value is returned.
The startTime obtained from perfNow
The startTime obtained from perfNow
The number of milliseconds that have elapsed since the startTime.
0.4.4
let start = perfNow();
// Do some work
let totalTime = elapsedTime(start);
-Generated using TypeDoc
Generated using TypeDoc
Encode the provided string to a safe HTML form, converting the base &
, <
, >
, \"
and '
+
Encode the provided string to a safe HTML form, converting the base &
, <
, >
, \"
and '
characters into their HTML encoded representations
The string value to be converted into a HTML safe form
+The string value to be converted into a HTML safe form
The converted string as HTML
0.9.0
encodeAsHtml("HelloDarkness"); // "HelloDarkness"
encodeAsHtml("Hello Darkness"); // "Hello Darkness"
encodeAsHtml("hello.Darkness"); // "hello.Darkness"
encodeAsHtml("hello-Darkness"); // "hello-Darkness"
encodeAsHtml("hello_Darkness"); // "hello_Darkness"
encodeAsHtml("abc-123"); // "abc-123"
encodeAsHtml("0abc0"); // "0abc0"
encodeAsHtml("\"HelloDarkness\""); // ""HelloDarkness""
encodeAsHtml("\"Hello Darkness\""); // ""Hello Darkness""
encodeAsHtml("\"hello Darkness\""); // ""hello Darkness""
encodeAsHtml("\"hello Darkness\""); // ""hello Darkness""
encodeAsHtml("\"hello .,#<[]>Darkness\""); // ""hello .,#<[]>Darkness""
encodeAsHtml("<script src=\"javascript:alert('Hello');\"></script>"); // "<script src="javascript:alert('Hello');"></script>"
-Generated using TypeDoc
Generated using TypeDoc
Encode the value into a JSON string, if the provided value is a string this will encode +
Encode the value into a JSON string, if the provided value is a string this will encode
any character that is not an alpha, numeric, space or some special characters as \uXXXX
and will always be returned wrapped in double quotes "xxx"
, if the value is any other
object it will be encoded using JSON.stringify() and if there is an exception encoding
with JSON.stringify() it will return the exception as a string using dumpObj().
The value to be encoded as JSON
-Optional
format: number | booleanIdentifies whether the JSON value should be formatted when an object
+The value to be encoded as JSON
+Optional
format: number | booleanIdentifies whether the JSON value should be formatted when an object
true
- Format with 4 spaces0.9.0
// String values
encodeAsJson("abc.123"); // "\"abc.123\""
encodeAsJson("321-abc"); // "\"321-abc\""
encodeAsJson("Hello darkness, my \"old\" friend..."); // "\"Hello darkness, my \\\"old\\\" friend...\""
encodeAsJson("Hello: Darkness"); // "\"Hello: Darkness\""
encodeAsJson("Hello\\u003A Darkness"); // "\"Hello\\\\u003A Darkness\""
encodeAsJson("`!@#$%^&*()_-+=[]{}:;'<>?"); // "\"\\u0060!@#$%^&*()_-+=[]{}:;\\u0027<>?\""
encodeAsJson("0"); // "\"0\""
encodeAsJson("1"); // "\"1\""
encodeAsJson([]); // "[]"
encodeAsJson(["A"]); // "[\"A\"]"
encodeAsJson([0]); // "[0]"
encodeAsJson([false]); // "[false]"
encodeAsJson(new Array(1)); // "[null]"
encodeAsJson(true); // "true",
encodeAsJson(false); // "false"
encodeAsJson({}); // "{}"
encodeAsJson({ Hello: "Darkness" }); // "{\"Hello\":\"Darkness\"}");
-Generated using TypeDoc
Generated using TypeDoc
The fnApply
function calls the specified fn
function with the given thisArg
as the this
value,
+
The fnApply
function calls the specified fn
function with the given thisArg
as the this
value,
and the optional argArray
arguments provided as an array (or an Array-Like Object).
Normally, when calling a function, the value of this
inside the function is the object that the
function was accessed on. With fnApply()
, you can assign an arbitrary value as this when calling an
@@ -8,13 +8,13 @@
that it needs to have a length property, and integer ("index") properties in the range (0..length - 1).
For example, you could use a NodeList, or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }
.
You can also use arguments
.
The function to be called
-The value of this
provided for the call to fn
. If the function is not in strict mode,
+
The function to be called
+The value of this
provided for the call to fn
. If the function is not in strict mode,
null
and undefined
will be replaced with the global object, and primitive values will be converted to objects.
Optional
argArray: ArrayLike<any>An array-like object, specifying the arguments with which fn
should be called, or null
or
+
Optional
argArray: ArrayLike<any>An array-like object, specifying the arguments with which fn
should be called, or null
or
undefined
if no arguments should be provided to the function.
The result of calling the function with the specified this
value and arguments.
0.9.8
// min / max number in an array
let max = fnApply(Math.max, null, [ 21, 42, 84, 168, 7, 3 ]);
// 168
let min = fnApply(Math.min, null, [ 21, 42, 84, 168, 7, 3 ]);
// 3
const module1 = {
prefix: "Hello",
x: 21,
getX() {
return this.x;
},
log(value: string) {
return this.prefix + " " + value + " : " + this.x
}
};
// The 'this' parameter of 'getX' is bound to 'module'.
module1.getX(); // 21
module1.log("Darkness"); // Hello Darkness : 21
// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
let module2 = {
prefix: "my",
x: 42
};
// Call the function of module1 with module2 as it's this
fnApply(module1.getX, module2); // 42
fnApply(module1.log, module2, [ "friend" ]); // my friend : 42
-Generated using TypeDoc
Generated using TypeDoc
Creates a new function that when called will set the value of thisArg
as the this
keyword
+
Creates a new function that when called will set the value of thisArg
as the this
keyword
value whrn calling the provided fn
instance, and all of the arguments passed to the new
function will be passed along to the original provided instance.
The value returned by the original fn
after executing with the provided thisArg
.
The value returned by the original fn
after executing with the provided thisArg
.
0.9.8
const module1 = {
x: 21,
getX() {
return this.x;
},
};
// The 'this' parameter of 'getX' is bound to 'module'.
console.log(module1.getX()); // 21
// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
let module2 = {
x: 42
};
module2.getX = fnBind(module1.getX, module2);
module2.getX(); // 42
// It can also be used to proxy to the original function from the new one
module2.getX = fnBind(module1.getX, module1);
module2.getX(); // 21
-Generated using TypeDoc
Generated using TypeDoc
The fnCall
function calls the function with the given thisArg
as the this
value and with
+
The fnCall
function calls the function with the given thisArg
as the this
value and with
al of the _args
provided as it's `arguments.
This is almost identical to
-fnApply
, except that the function arguments are passed tofnCall
@@ -15,6 +15,6 @@null
andundefined
will be replaced with the global object, and primitive values will be converted to objects. @param _args - The zero or more arguments to be passed to thefn
function. @returns The result of calling the function with the specifiedthis
value and arguments.
// min / max number in an array
let max = fnCall(Math.max, null, 21, 42, 84, 168, 7, 3);
// 168
let min = fnCall(Math.min, null, 21, 42, 84, 168, 7, 3);
// 3
const module1 = {
prefix: "Hello",
x: 21,
getX() {
return this.x;
},
log(value: string) {
return this.prefix + " " + value + " : " + this.x
}
};
// The 'this' parameter of 'getX' is bound to 'module'.
module1.getX(); // 21
module1.log("Darkness"); // Hello Darkness : 21
// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
let module2 = {
prefix: "my",
x: 42
};
// Call the function of module1 with module2 as it's this
fnCall(module1.getX, module2); // 42
fnCall(module1.log, module2, "friend"); // my friend : 42
+
// min / max number in an array
let max = fnCall(Math.max, null, 21, 42, 84, 168, 7, 3);
// 168
let min = fnCall(Math.min, null, 21, 42, 84, 168, 7, 3);
// 3
const module1 = {
prefix: "Hello",
x: 21,
getX() {
return this.x;
},
log(value: string) {
return this.prefix + " " + value + " : " + this.x
}
};
// The 'this' parameter of 'getX' is bound to 'module'.
module1.getX(); // 21
module1.log("Darkness"); // Hello Darkness : 21
// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
let module2 = {
prefix: "my",
x: 42
};
// Call the function of module1 with module2 as it's this
fnCall(module1.getX, module2); // 42
fnCall(module1.log, module2, "friend"); // my friend : 42
-Generated using TypeDoc
Generated using TypeDoc
Deep copy handler to identify and copy functions. This handler just returns the original +
Deep copy handler to identify and copy functions. This handler just returns the original function so the original function will be assigned to any new deep copied instance.
-The details object for the current property being copied
+The details object for the current property being copied
true
if the current value is a function otherwise false
0.4.4
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Returns the current global scope object, for a normal web page this will be the current +
Returns the current global scope object, for a normal web page this will be the current window, for a Web Worker this will be current worker global scope via "self". The internal implementation returns the first available instance object in the following order
Optional
useCached: boolean[Optional] used for testing to bypass the cached lookup, when true
this will
+
Optional
useCached: boolean[Optional] used for testing to bypass the cached lookup, when true
this will
cause the cached global to be reset.
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Return the named global object if available, will return null if the object is not available.
-The globally named object, may be any valid property key (string, number or symbol)
-Optional
useCached: boolean[Optional] used for testing to bypass the cached lookup, when true
this will
+
Return the named global object if available, will return null if the object is not available.
+The globally named object, may be any valid property key (string, number or symbol)
+Optional
useCached: boolean[Optional] used for testing to bypass the cached lookup, when true
this will
cause the cached global to be reset.
// This does not cause the evaluation to occur
window.myGlobal = "Hello";
let cachedValue = getInst("myGlobal");
// cachedValue === "Hello"
window.myGlobal = "Darkness";
// getInst("myGlobal") === "Darkness"
let promiseCls = getInst("Promise");
// May throw if the global is not supported by the runtime
// otherwise the Promise class.
-Generated using TypeDoc
Generated using TypeDoc
Helper to obtain the integer value using base 10 conversion from a string, +
Helper to obtain the integer value using base 10 conversion from a string,
also handles null
, undefined
and Nan
cases which will all return the
default value.
Optional
value: string | numberThe string or numeric value to get the integer value from
-Optional
defValue: numberThe default value if unsuccessful
+Optional
value: string | numberThe string or numeric value to get the integer value from
+Optional
defValue: numberThe default value if unsuccessful
The default or parsed value.
-Generated using TypeDoc
Generated using TypeDoc
If Symbols are supported then get the property of the global Symbol, if Symbol's are +
If Symbols are supported then get the property of the global Symbol, if Symbol's are not supported and noPoly is true it returns null. Used to access the well known symbols.
-The property name to return (if it exists) for Symbol
-Optional
noPoly: booleanFlag indicating whether to return a polyfill if symbols are not supported.
+The property name to return (if it exists) for Symbol
+Optional
noPoly: booleanFlag indicating whether to return a polyfill if symbols are not supported.
The value of the property if present
// If Symbol is supported in the runtime
getKnownSymbol("toStringTag") === Symbol.toStringTag; // true
getKnownSymbol(WellKnownSymbols.toStringTag) === Symbol.toStringTag; // true
-Generated using TypeDoc
Generated using TypeDoc
Create and return an readonly ILazyValue instance which will cache and return the value returned +
Create and return an readonly ILazyValue instance which will cache and return the value returned by the callback function. The callback function will only be called once, multiple access of the value does not cause re-execution of the callback as the result from the first call is cached internally.
-The callback function to fetch the value to be lazily evaluated and cached
+A new readonly ILazyValue instance which wraps the callback and will be used to cache the result of the callback
0.4.5
// This does not cause the evaluation to occur
let cachedValue = getLazy(() => callSomeExpensiveFunction());
let theValue;
// Just checking if there is an object still does not cause the evaluation
if (cachedValue) {
// This will cause the evaluation to occur and the result will be cached
theValue = cachedValue.v;
}
// Accessing the value again will not cause the re-evaluation to occur, it will just return the same
// result value again.
theValue === cachedValue.v; // true
-Generated using TypeDoc
Generated using TypeDoc
Helper to return the length value of an object, this will return the value +
Helper to return the length value of an object, this will return the value of the "length" property. Generally used to return the length of a string or array.
-The value to return the length property from, must contain a length
property
The value to return the length property from, must contain a length
property
0.4.2
getLength(""); // returns 0
getLength("Hello World"); // returns 11
getLength([]); // returns 0;
getLength([0, 1, 2, 3]); // returns 4;
getLength({ length: 42}); // returns 42
getLength({ length: () => 53; }); // returns the function that if called would return 53
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Returns the global performance
Object if available, which can be used to
+
Returns the global performance
Object if available, which can be used to
gather performance information about the current document. It serves as the
point of exposure for the Performance Timeline API, the High Resolution Time
API, the Navigation Timing API, the User Timing API, and the Resource Timing API.
The global performance object if available.
0.4.4
-Generated using TypeDoc
Generated using TypeDoc
If Symbols are supported then attempt to return the named Symbol
+Generated using TypeDoc
Generated using TypeDoc
Get the named value from the target object where the path is represented by the string iterator +
Get the named value from the target object where the path is represented by the string iterator or iterable to separate the nested objects of the heirarchy / path to the value. If the target does not contain the full path the iterator will not be completed.
The order of processing of the iterator is not reset if you add or remove elements to the iterator, the actual behavior will depend on the iterator imeplementation.
If the passed iter
is both an Iterable
The source object that contains the value
-The iter identifying the path of the final key value
-Optional
defValue: VIf the final value or any intervening object in the heirarchy is not present +
The value located based on the path or the defaule value
0.9.1
let theValue = {
Hello: {
Darkness: {
my: "old"
}
},
friend: "I've",
come: {
to: {
see: "you"
}
}
};
let value = getValueByKey(theValue, ["Hello", "Darkness", "my"], "friend");
// value === "my"
let value = getValueByKey(theValue, ["My", "Old"], "friend");
// value === "friend"
let value = getValueByKey(theValue, ["come", "to"], "friend");
// value === { see: "you" }
let value = getValueByKey(theValue, ["friend"], "friend");
// value === "I've"
-Generated using TypeDoc
Generated using TypeDoc
Get the named value from the target object where the path may be presented by a string which +
Get the named value from the target object where the path may be presented by a string which contains "." characters to separate the nested objects of the heirarchy / path to the value.
-The source object that contains the value
-The path identifing the location where the value should be located
-Optional
defValue: VIf the final value or any intervening object in the heirarchy is not present +
The value located based on the path or the defaule value
0.9.1
let theValue = {
Hello: {
Darkness: {
my: "old"
}
},
friend: "I've",
come: {
to: {
see: "you"
}
}
};
let value = getValueByKey(theValue, "Hello.Darkness.my", "friend");
// value === "my"
let value = getValueByKey(theValue, "My.Old", "friend");
// value === "friend"
let value = getValueByKey(theValue, "come.to", "friend");
// value === { see: "you" }
let value = getValueByKey(theValue, "friend", "friend");
// value === "I've"
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Identify whether the runtime contains a document
object
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Identifies if the runtime supports the requestIdleCallback
API.
Identifies if the runtime supports the requestIdleCallback
API.
True if the runtime supports requestIdleCallback
otherwise false.
0.4.4
let nativeIdleTimeouts = hasIdleCallback();
// true === idle timeouts are supported by the runtime otherwise false and the {@linke scheduleIdleCallback}
will use `setTimeout` instead.
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Identify whether the runtimne contains a performance
object
Generated using TypeDoc
Generated using TypeDoc
Helper to identify whether the runtime support the Symbols either via native or an installed polyfill
+Generated using TypeDoc
Generated using TypeDoc
Return whether the value appears to have any value
, this helper returns true for
Return whether the value appears to have any value
, this helper returns true for
The value to be checked
+The value to be checked
// False
hasValue(null); // false
hasValue(undefined); // false
hasValue("undefined"); // false (Special Case)
hasValue(""); // false -- use: !strIsNullOrEmpty("")
hasValue([]); // false
hasValue(/[a-z]/g); // false
hasValue(new RegExp("")); // false
hasValue(new ArrayBuffer(0)); // false
hasValue(new Error("Test Error")); // false
hasValue(new TypeError("Test TypeError")); // false
hasValue(new TestError("Test TestError")); // false
hasValue(Promise.reject()); // false
hasValue(Promise.resolve()); // false
hasValue(new Promise(() => {})); // false
hasValue({}); // false
hasValue(Object.create(null)); // false
hasValue(polyObjCreate(null)); // false
// Objects with length / size property or function
hasValue({ length: 0 }); // false
hasValue({ length: () => 0 }); // false
hasValue({ byteLength: 0 }); // false
hasValue({ byteLength: () => 0 }); // false
hasValue({ size: 0 }); // false
hasValue({ size: () => 0 }); // false
hasValue({ count: 0 }); // false
hasValue({ count: undefined as any }); // false
hasValue({ count: null as any }); // false
hasValue({ count: () => 0 }); // false
hasValue({ count: () => undefined as any }); // false
hasValue({ count: () => null as any }); // false
hasValue({ valueOf: () => undefined as any});// false
hasValue({ valueOf: () => null as any }); // false
// True
hasValue("null"); // true
hasValue("0"); // true
hasValue("1"); // true
hasValue("aa"); // true
hasValue(new Date()); // true
hasValue(0); // true
hasValue(1); // true
hasValue(_dummyFunction); // true
hasValue(["A"]); // true
hasValue([0]); // true
hasValue([false]); // true
hasValue(new Array(1)); // true
hasValue(true); // true
hasValue(false); // true
hasValue("true"); // true
hasValue("false"); // true
hasValue((/[a-z]/g).exec("hello")); // true
hasValue(new ArrayBuffer(1)); // true
hasValue(_dummyError()); // true
hasValue(_simplePromise()); // true
hasValue(_simplePromiseLike()); // true
// Boolean objects
hasValue(new Boolean(true)); // true
hasValue(new Boolean(false)); // true
hasValue(new Boolean("true")); // true
hasValue(new Boolean("false")); // true
hasValue(new Boolean("0")); // true
hasValue(new Boolean(0)); // true
hasValue(new Boolean("1")); // true
hasValue(new Boolean(1)); // true
// Boolean values
hasValue(Boolean(true)); // true
hasValue(Boolean(false)); // true
hasValue(Boolean("true")); // true
hasValue(Boolean("false")); // true
hasValue(Boolean("0")); // true
hasValue(Boolean(0)); // true
hasValue(Boolean("1")); // true
hasValue(Boolean(1)); // true
// Objects with length / size property or function
hasValue({ length: 1 }); // true
hasValue({ length: () => 1 }); // true
hasValue({ byteLength: 1 }); // true
hasValue({ byteLength: () => 1 }); // true
hasValue({ size: 1 }); // true
hasValue({ size: () => 1 }); // true
hasValue({ count: 1 }); // true
hasValue({ count: () => 1 }); // true
hasValue({ valueOf: () => 0 }); // true
hasValue({ valueOf: () => 1 }); // true
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is an Array.
-True if the value is a Array, false otherwise.
+Checks if the type of value is an Array.
+True if the value is a Array, false otherwise.
import { isArray, isObject } from "@nevware21/ts-utils";
function performAction(value: any) {
if (isArray(value) || isObject(value)) {
// Do something
} else {
// Do something else
}
}
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a ArrayBuffer object.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a Blob object.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a boolean.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Check if an object is of type Date
-import { isDate } from "@nevware21/ts-utils";
let _theDate = null;
function getSetDate(newDate?: any) {
_theDate = isDate(newDate) ? newDate : new Date();
return _theDate;
}
+isDate | @nevware21/ts-utils Generated using TypeDoc
\ No newline at end of file
+
Generated using TypeDoc
Checks if the passed value is defined, which means it has any value and is not undefined. +
Checks if the passed value is defined, which means it has any value and is not undefined. A string value of "undefined" is considered to be defined.
-The value to check
+The value to check
true if arg has a value (is not === undefined)
isDefined(null); // false
isDefined(undefined); // false
isDefined("undefined"); // true
let value = null;
isDefined(value); // false
let value = undefined;
isDefined(value); // false
isDefined(""); // true
isDefined(0); // true
isDefined(new Date()); // true
isDefined(true); // true
isDefined(false); // true
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a Error object.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a File object.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a FormData object.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks to see if the past value is a function value
-The value to check
+Checks to see if the past value is a function value
+The value to check
function myFunction() { }
isFunction(null); // false
isFunction(undefined); // false
isFunction("null"); // false
isFunction("undefined"); // false
isFunction("1"); // false
isFunction("aa"); // false
isFunction(new Date()); // false
isFunction(1); // false
isFunction(""); // false
isFunction(myFunction); // true
isFunction([]); // false
isFunction(new Array(1)); // false
-Generated using TypeDoc
Generated using TypeDoc
Checks if the value looks like it is iterable, contains a [symbol.iterator].
-The value to be checked
+Checks if the value looks like it is iterable, contains a [symbol.iterator].
+The value to be checked
True if the value is an Iterable, otherwise false
0.4.0
isIterable(null); // false
isIterable(undefined); // false
isIterable("null"); // true (Strings are iterable)
isIterable([]); // true (Arrays are iterable)
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value looks like an iterator instance (contains a next function).
-The value to be checked
+Checks if the type of value looks like an iterator instance (contains a next function).
+The value to be checked
True if the value is an Iterator, otherwise false
0.4.0
isIterator(null); // false
isIterator(undefined); // false
isIterator("null"); // false (Strings are iterable but not iterators)
isIterator([]); // false (Arrays are iterable but not iterators)
isIterator({
next: function() { return true }
}); // true, iterators must contain a "next" function
-Generated using TypeDoc
Generated using TypeDoc
Simple method to determine if we are running in a node environment
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value does not evaluate to true value, handling some special +
Checks if the type of value does not evaluate to true value, handling some special case usages of Boolean(true/false) and new Boolean(true/false).
-Value to be checked.
+Value to be checked.
True if the value is not truthy, false otherwise.
-Generated using TypeDoc
Generated using TypeDoc
Checks if the provided value is null, undefined or contains the string value of "undefined".
-The value to check
+Checks if the provided value is null, undefined or contains the string value of "undefined".
+The value to check
true
if the value is null
or undefined
isNullOrUndefined(null); // true
isNullOrUndefined(undefined); // true
isNullOrUndefined("undefined"); // true
let value = null;
isNullOrUndefined(value); // true
let value = undefined;
isNullOrUndefined(value); // true
isNullOrUndefined(""); // false
isNullOrUndefined(0); // false
isNullOrUndefined(new Date()); // false
isNullOrUndefined(true); // false
isNullOrUndefined(false); // false
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a number.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Checks to see if the past value is a plain object (not a class/array) value. +
Checks to see if the past value is a plain object (not a class/array) value.
Object are considered to be "plain" if they are created with no prototype Object.create(null)
or by using the Object global (native) function, all other "objects" ar
The value to check
+The value to check
true if value
is a normal plain object
0.4.4
console.log(isPlainObject({ 0: 'a', 1: 'b', 2: 'c' })); // true
console.log(isPlainObject({ 100: 'a', 2: 'b', 7: 'c' })); // true
console.log(isPlainObject(objCreate(null))); // true
const myObj = objCreate({}, {
getFoo: {
value() { return this.foo; }
}
});
myObj.foo = 1;
console.log(isPlainObject(myObj)); // true
console.log(isPlainObject(['a', 'b', 'c'])); // false
console.log(isPlainObject(new Date())); // false
console.log(isPlainObject(new Error("An Error"))); // false
console.log(isPlainObject(null)); // false
console.log(isPlainObject(undefined)); // false
console.log(isPlainObject("null")); // false
console.log(isPlainObject("undefined")); // false
console.log(isPlainObject("1")); // false
console.log(isPlainObject("aa")); // false
-Generated using TypeDoc
Generated using TypeDoc
Identifies whether the provided value is a JavaScript primitive +
Identifies whether the provided value is a JavaScript primitive which is when is it not an object and has no methods or properties. There are 7 primitive data types:
The value to check whether it's a primitive value
+The value to check whether it's a primitive value
0.4.4
isPrimitive(null); // true
isPrimitive(undefined); // true
isPrimitive("null"); // true
isPrimitive("undefined"); // true
isPrimitive("1"); // true
isPrimitive("aa"); // true
isPrimitive(1); // true
isPrimitive(Number(2)); // true
isPrimitive(""); // true
isPrimitive(String("")); // true
isPrimitive(true); // true
isPrimitive(false); // true
isPrimitive("true"); // true
isPrimitive("false"); // true
isPrimitive(BigInt(42)); // true
isPrimitive(Symbol.for("Hello")); // true
isPrimitive(new String("aa")); // false
isPrimitive(new Date()); // false
isPrimitive(_dummyFunction); // false
isPrimitive([]); // false
isPrimitive(new Array(1)); // false
isPrimitive(new Boolean(true)); // false
isPrimitive(new Boolean(false)); // false
isPrimitive(new Boolean("true")); // false
isPrimitive(new Boolean("false")); // false
-Generated using TypeDoc
Generated using TypeDoc
Identifies whether the provided value is a JavaScript primitive +
Identifies whether the provided value is a JavaScript primitive which is when is it not an object and has no methods or properties. There are 6 primitive data types:
The type as a string value to be checked whther it's a primitive type, this should be the value +
The type as a string value to be checked whther it's a primitive type, this should be the value
returned from typeof value
.
0.9.6
isPrimitiveType(null); // false
isPrimitiveType(undefined); // false
isPrimitiveType("null"); // false
isPrimitiveType("undefined"); // false
isPrimitiveType("1"); // false
isPrimitiveType("aa"); // false
isPrimitiveType(1); // false
isPrimitiveType(Number(2)); // false
isPrimitiveType(""); // false
isPrimitiveType(String("")); // false
isPrimitiveType(true); // false
isPrimitiveType(false); // false
isPrimitiveType("true"); // false
isPrimitiveType("false"); // false
isPrimitiveType(BigInt(42)); // false
isPrimitiveType(Symbol.for("Hello")); // false
isPrimitiveType("string"); // true
isPrimitiveType("number"); // true
isPrimitiveType("boolean"); // true
isPrimitiveType("undefined"); // true
isPrimitiveType("symbol"); // true
isPrimitiveType("bigint"); // true
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a Promise instance (contains then and catch functions).
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a PromiseLike instance (contains a then function).
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Determines if a value is a regular expression object.
-Reference to check.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the provided value is null, undefined only, a string value of "undefined" is NOT considered +
Checks if the provided value is null, undefined only, a string value of "undefined" is NOT considered to be undefined.
-The value to check
+The value to check
isStrictNullOrUndefined(null); // true
isStrictNullOrUndefined(undefined); // true
isStrictNullOrUndefined("undefined"); // false
let value = null;
isStrictNullOrUndefined(value); // true
let value = undefined;
isStrictNullOrUndefined(value); // true
isStrictNullOrUndefined(""); // false
isStrictNullOrUndefined(0); // false
isStrictNullOrUndefined(new Date()); // false
isStrictNullOrUndefined(true); // false
isStrictNullOrUndefined(false); // false
-Generated using TypeDoc
Generated using TypeDoc
Checks if the provided value is undefined, a string value of "undefined" is NOT considered +
Checks if the provided value is undefined, a string value of "undefined" is NOT considered to be undefined.
-The value to check
+The value to check
true if the typeof value === UNDEFINED
isStrictUndefined(undefined); // true
isStrictUndefined(null); // false
isStrictUndefined("null"); // false
isStrictUndefined("undefined"); // false
isStrictUndefined("1"); // false
isStrictUndefined("aa"); // false
isStrictUndefined(new Date()); // false
isStrictUndefined(0); // false
isStrictUndefined(1); // false
isStrictUndefined(""); // false
-Generated using TypeDoc
Generated using TypeDoc
Checks to see if the past value is a string value
-The value to check
+Checks to see if the past value is a string value
+The value to check
isString(""); // true
isString("null"); // true
isString("undefined"); // true
isString(String("")); // true
isString(null); // false
isString(undefined); // false
isString(0); // false
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a symbol.
-Value to be checked.
+Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value is a PromiseLike instance (contains a then function). +
Checks if the type of value is a PromiseLike instance (contains a then function). This is an alias for isPromiseLike.
-Value to be checked.
+Value to be checked.
True if the value is a PromiseLike, false otherwise.
-Generated using TypeDoc
Generated using TypeDoc
Checks if the type of value evaluates to true value, handling some special +
Checks if the type of value evaluates to true value, handling some special case usages of Boolean(true/false) and new Boolean(true/false).
-Value to be checked.
+Value to be checked.
True if the value is not truthy, false otherwise.
-Generated using TypeDoc
Generated using TypeDoc
Validate if the provided value object is of the expected type
-The value to check
-The expected type name as a string
+Generated using TypeDoc
Generated using TypeDoc
Checks if the provided value is undefined or contains the string value "undefined", +
Checks if the provided value is undefined or contains the string value "undefined", if you want to consider the string value as undefined see isStrictUndefined
-The value to check
+The value to check
true if the value is undefined or "undefined", otherwise false
isUndefined(undefined); // true
isUndefined("undefined"); // true
isUndefined(null); // false
isUndefined("null"); // false
isUndefined("1"); // false
isUndefined("aa"); // false
isUndefined(new Date()); // false
isUndefined(1); // false
isUndefined(""); // false
isUndefined(_dummyFunction); // false
isUndefined([]); // false
isUndefined(new Array(1)); // false
isUndefined(true); // false
isUndefined(false); // false
isUndefined("true"); // false
isUndefined("false"); // false
isUndefined(new Boolean(true)); // false
isUndefined(new Boolean(false)); // false
isUndefined(new Boolean("true")); // false
isUndefined(new Boolean("false")); // false
isUndefined(Boolean(true)); // false
isUndefined(Boolean(false)); // false
isUndefined(Boolean("true")); // false
isUndefined(Boolean("false")); // false
isUndefined(new RegExp("")); // false
isUndefined(new ArrayBuffer(0)); // false
isUndefined(new Error("Test Error"));// false
isUndefined(new TypeError("Test TypeError")); // false
isUndefined(new TestError("Test TestError")); // false
isUndefined(_dummyError()); // false
isUndefined(Promise.reject()); // false
isUndefined(Promise.resolve()); // false
isUndefined(new Promise(() => {})); // false
isUndefined(_simplePromise()); // false
isUndefined(_simplePromiseLike()); // false
isUndefined(Object.create(null)); // false
isUndefined(polyObjCreate(null)); // false
-Generated using TypeDoc
Generated using TypeDoc
Helper to identify if you are running as a Dedicated, Shared or Service worker
+Generated using TypeDoc
Generated using TypeDoc
Calls the provided callbackFn
function once for each element in the iterator or iterator returned by
+
Calls the provided callbackFn
function once for each element in the iterator or iterator returned by
the iterable and processed in the same order as returned by the iterator. As with the arrForEach
you CAN stop / break the iteration by returning -1 from thecallbackFn
function.
The order of processing is not reset if you add or remove elements to the iterator, the actual behavior will depend on the iterator imeplementation.
If the passed iter
is both an Iterable
A synchronous
function that accepts up to three arguments. iterForOf calls the
+
A synchronous
function that accepts up to three arguments. iterForOf calls the
callbackfn function one time for each element returned by the iterator.
Optional
thisArg: anyAn object to which the this keyword can refer in the callbackfn function. If thisArg is +
Optional
thisArg: anyAn object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, null or undefined the iterator will be used as the this value.
If Symbols are NOT supported then the iterable MUST be using the same polyFill for the well know symbols, if you are targetting a mixed environment you SHOULD either
@@ -22,4 +22,4 @@0.4.2
Any exception thrown while processing the iterator
const items = {
'item1': 'value1',
'item2': 'value2',
'item3': 'value3
};
const copyItems = [];
iterForOf(items, (item) => {
copyItems.push(item);
// May return -1 to abort the iteration
});
-Generated using TypeDoc
Generated using TypeDoc
Create and return an readonly ILazyValue instance which will cache and return the named global +
Create and return an readonly ILazyValue instance which will cache and return the named global
value if available, will return null
if the named global object is not available or if the runtime
throws an exception when attempting to access the global object.
Unlike getInst the value is cached after the first access, so if the global value changes after
the initial fetch the original cached value is still returned.
The name of the global object to get, may be any valid PropertyKey (string, number or symbol)
+The name of the global object to get, may be any valid PropertyKey (string, number or symbol)
A new readonly ILazyValue instance which will lazily attempt to return the globally available named instance.
0.9.5
// This does not cause the evaluation to occur
window.myGlobal = "Hello";
let cachedValue = lazySafeGetInst("myGlobal");
// cachedValue.v === "Hello"
window.myGlobal = "Darkness";
// cachedValue.v === "Hello"
let promiseCls = lazySafeGetInst("Promise");
// null if Promise is not supported in the runtime
// otherwise the Promise class.
-Generated using TypeDoc
Generated using TypeDoc
Create a simple glob style regular expression from the string value, converting '**'
, '*'
and '?'
+
Create a simple glob style regular expression from the string value, converting '**'
, '*'
and '?'
characters. Unlike createFilenameRegex the '*'
and '?'
will NOT match folder seperator
characters '/'
and '\'
.
If the source string contains folder seperators both '/'
and '\'
are treated as synonomous
@@ -11,13 +11,13 @@
'/'
Matches either '/'
or '\'
character, not captured as a group'\'
Matches either '/'
or '\'
character, not captured as a groupThe string value to converted.
-Optional
ignoreCase: booleanFlag to indicate whether the regular expression should be case-sensitive, Defaults +
The string value to converted.
+Optional
ignoreCase: booleanFlag to indicate whether the regular expression should be case-sensitive, Defaults to false.
-Optional
fullMatch: booleanFlag to identify whether the RegExp should be wrapped with '^'
and '$'
to
+
Optional
fullMatch: booleanFlag to identify whether the RegExp should be wrapped with '^'
and '$'
to
incidate match the entire string only.
The new Regular Expression created from the provided value.
0.9.0
let regex = makeGlobRegex("src\\**\\*.ts");
let matches = regex.exec("Hello");
matches; // null
let matches = regex.exec("Src/index.ts");
matches; // null - Specify the ignoreCase if you want this to match
let matches = regex.exec("src/index.ts");
matches[0]; // "src/index.ts"
matches[1]; // undefined;
matches[2]; // "index"
let matches = regex.exec("src\\index.ts");
matches[0]; // "src\\index.ts"
matches[1]; // undefined;
matches[2]; // "index"
let matches = regex.exec("src/helpers/regexp.ts");
matches[0]; // "src/helpers/regexp.ts"
matches[1]; // "helpers/"
matches[2]; // "regexp"
let matches = regex.exec("src\\helpers/regexp.ts");
matches[0]; // "src\\helpers/regexp.ts"
matches[1]; // "helpers/"
matches[2]; // "regexp"
let matches = regex.exec(" src/index.tsx ");
matches[0]; // "src/index.ts"
matches[1]; // undefined
matches[2]; // "index"
let matches = regex.exec(" src/helpers/regexp.ts. ");
matches[0]; // "src/helpers/regexp.ts"
matches[1]; // "helpers/"
matches[2]; // "regexp"]);
-Generated using TypeDoc
Generated using TypeDoc
Adds or replaces an iterable implementation that conforms to the Iterable
protocol to the target instance, it
+
Adds or replaces an iterable implementation that conforms to the Iterable
protocol to the target instance, it
uses the provided ctx
to create an Iterator
via createIterator.
The context used to manage the iteration over the items.
+The context used to manage the iteration over the items.
A new Iterable instance
0.4.2
let current = 0;
let next = 1;
let done = false;
let fibCtx: CreateIteratorContext<number> = {
n: function() {
fibCtx.v = current;
current = next;
next = fibCtx.v + next;
// Return not done, so it will just continue
return false;
}
};
let values: number[] = [];
let theIterable: Iterable<T> = makeIterable({}, fibCtx);
iterForOf(theIterable, (value) => {
values.push(value);
if (values.length === 10) {
return -1;
}
});
// Values: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
-Generated using TypeDoc
Generated using TypeDoc
The mathCeil()
function always rounds a number up to the next largest integer.
Generated using TypeDoc
The mathFloor()
function returns the largest integer less than or equal to a given number.
Generated using TypeDoc
The mathMax()
function returns the largest of the zero or more numbers given as input
+
The mathMax()
function returns the largest of the zero or more numbers given as input
parameters, or NaN if any parameter isn't a number and can't be converted into one.
If no arguments are given, the result is -Infinity.
If at least one of arguments cannot be converted to a number, the result is NaN.
-Rest
...values: number[]Zero or more numbers among which the largest value will be selected and returned.
+Rest
...values: number[]Zero or more numbers among which the largest value will be selected and returned.
The largest of the given numbers. If any one or more of the parameters cannot be converted into a number, NaN is returned. The result is -Infinity if no parameters are provided.
0.4.2
mathMax(10, 20); // 20
mathMax(-10, -20); // -10
mathMax(-10, 20); // 20
-Generated using TypeDoc
Generated using TypeDoc
The mathMin() function returns the lowest-valued number passed into it, or NaN if any +
The mathMin() function returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one.
If no arguments are given, the result is Infinity.
If at least one of arguments cannot be converted to a number, the result is NaN.
-Rest
...values: number[]Zero or more numbers among which the lowest value will be selected and returned.
+Rest
...values: number[]Zero or more numbers among which the lowest value will be selected and returned.
The smallest of the given numbers. If any one or more of the parameters cannot be converted into a number, NaN is returned. The result is Infinity if no parameters are provided.
0.4.2
const x = 10, y = -20;
const z = Math.min(x, y); // -20
-Generated using TypeDoc
Generated using TypeDoc
Convert the provided value to an integer
-The value to be converted to an integer.
-Optional
throwInfinity: boolean[Optional] Throws RangeError if value is Infinity, defaults to false
+Generated using TypeDoc
Generated using TypeDoc
The mathTrunc()
function returns the integer part of a number by removing any fractional digits.
+
The mathTrunc()
function returns the integer part of a number by removing any fractional digits.
Unlike the other three Math methods: Math.floor(), Math.ceil() and Math.round(), the way mathTrunc()
works is very simple. It truncates (cuts off) the dot and the digits to the right of it, no matter
whether the argument is a positive or negative number.
The argument passed to this method will be converted to number type implicitly.
The integer path of the given number
-Generated using TypeDoc
The integer path of the given number
+Generated using TypeDoc
Returns a new unique Symbol value. If noPoly is true and symbols are not supported +
Returns a new unique Symbol value. If noPoly is true and symbols are not supported then this will return null.
-Optional
description: string | numberDescription of the new Symbol object.
-Optional
noPoly: booleanFlag indicating whether to return a polyfil if symbols are not supported.
+Optional
description: string | numberDescription of the new Symbol object.
+Optional
noPoly: booleanFlag indicating whether to return a polyfil if symbols are not supported.
The new symbol
-Generated using TypeDoc
Generated using TypeDoc
Validates that the string name conforms to the JS IdentifierName specification and if not +
Validates that the string name conforms to the JS IdentifierName specification and if not normalizes the name so that it would. This method does not identify or change any keywords meaning that if you pass in a known keyword the same value will be returned.
-The string value to validate
-Optional
camelCase: booleanOptionally (see [1]) convert into CamelCase with the leading character either
+The string value to validate
+Optional
camelCase: booleanOptionally (see [1]) convert into CamelCase with the leading character either
true
=> lowercase0.9.0
normalizeJsName("HelloDarkness"); // "HelloDarkness"
normalizeJsName("Hello Darkness"); // "Hello_Darkness"
normalizeJsName("hello Darkness"); // "hello_Darkness"
normalizeJsName("hello Darkness"); // "hello_Darkness"
normalizeJsName("hello.Darkness"); // "hello_Darkness"
normalizeJsName("hello-Darkness"); // "hello_Darkness"
normalizeJsName("hello_Darkness"); // "hello_Darkness"
normalizeJsName("abc-123"); // "abc_123"
normalizeJsName("0abc0"); // "0abc0"
normalizeJsName("\"HelloDarkness\""); // "_HelloDarkness_"
normalizeJsName("\"Hello Darkness\""); // "_Hello_Darkness_"
normalizeJsName("\"hello Darkness\""); // "_hello_Darkness_"
normalizeJsName("\"hello Darkness\""); // "_hello_Darkness_"
normalizeJsName("\"hello .,#[]Darkness\""); // "_hello______Darkness_"
normalizeJsName("HelloDarkness", true); // "helloDarkness"
normalizeJsName("Hello Darkness", true); // "helloDarkness"
normalizeJsName("hello Darkness", true); // "helloDarkness"
normalizeJsName("hello Darkness", true); // "helloDarkness"
normalizeJsName("hello.Darkness", true); // "helloDarkness"
normalizeJsName("hello-Darkness", true); // "helloDarkness"
normalizeJsName("hello_Darkness", true); // "helloDarkness"
normalizeJsName("abc-123", true); // "abc123"
normalizeJsName("0abc0", true); // "0abc0"
normalizeJsName("\"HelloDarkness\"", true); // "helloDarkness"
normalizeJsName("\"Hello Darkness\"", true); // "helloDarkness"
normalizeJsName("hello \"Darkness\"", true); // "helloDarkness"
normalizeJsName("hello \"Darkness\"", true); // "helloDarkness"
normalizeJsName("\"hello .,#[]Darkness\"", true); // "helloDarkness"
-Generated using TypeDoc
Generated using TypeDoc
The objAssign()
method copies all enumerable own properties from one or more source objects
+
The objAssign()
method copies all enumerable own properties from one or more source objects
to a target object. It returns the modified target object.
Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.
@@ -13,9 +13,9 @@Both String and Symbol properties are copied.
In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.
-const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
+
const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
-The objAssign()
method copies all enumerable own properties from one or more source objects
+
The objAssign()
method copies all enumerable own properties from one or more source objects
to a target object. It returns the modified target object.
Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.
@@ -30,9 +30,9 @@Both String and Symbol properties are copied.
In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.
-const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
+
const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
-The objAssign()
method copies all enumerable own properties from one or more source objects
+
The objAssign()
method copies all enumerable own properties from one or more source objects
to a target object. It returns the modified target object.
Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.
@@ -47,9 +47,9 @@Both String and Symbol properties are copied.
In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.
-const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
+
const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
-The objAssign()
method copies all enumerable own properties from one or more source objects
+
The objAssign()
method copies all enumerable own properties from one or more source objects
to a target object. It returns the modified target object.
Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.
@@ -64,6 +64,6 @@Both String and Symbol properties are copied.
In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.
-Rest
...sources: any[]const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
+
Rest
...sources: any[]const obj = { a: 1 };
const copy = objAssign({}, obj);
console.log(copy); // { a: 1 }
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = objAssign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
-Generated using TypeDoc
Generated using TypeDoc
Object helper to copy all of the enumerable properties from the source object to the target, the +
Object helper to copy all of the enumerable properties from the source object to the target, the properties are copied via objDeepCopy. Automatic handling of recursive properties was added in v0.4.4
-The target object to populated
-The source object to copy the properties from
-Optional
handler: ObjDeepCopyHandlerAn optional callback that lets you provide / overide the deep cloning (Since 0.4.4)
+The target object to populated
+The source object to copy the properties from
+Optional
handler: ObjDeepCopyHandlerAn optional callback that lets you provide / overide the deep cloning (Since 0.4.4)
The target object
let a: any = { a: 1 };
let b: any = { b: 2, d: new Date(), e: new TestClass("Hello Darkness") };
a.b = b; // { a: 1, b: { b: 2} }
b.a = a; // { a: 1, b: { b: 2, a: { a: 1, { b: 2, a: ... }}}}
function copyHandler(details: IObjDeepCopyHandlerDetails) {
// details.origin === a
// details.path[] is the path to the current value
if (details.value && isDate(details.value)) {
// So for the date path === [ "b", "d" ] which represents
// details.origin["b"]["d"] === The Date
// Create a clone the Date object and set as the "newValue"
details.value = new Date(details.value.getTime());
// Return true to indicate that we have "handled" the conversion
// See objDeepCopy example for just reusing the original value (just don't replace details.value)
return true;
}
return false;
}
let c: any = objCopyProps({}, a, copyHandler);
assert.notEqual(a, c, "check a and c are not the same");
assert.ok(c !== c.b.a, "The root object won't be the same for the target reference as are are copying properties to our target");
assert.ok(c.b === c.b.a.b, "Check that the 2 'b' references are the same object");
assert.ok(c.b.a === c.b.a.b.a, "Check that the 2 'a' references are the same object");
assert.ok(c.b.d === c.b.a.b.d, "Check that the 2 'd' references are the same object");
assert.ok(isDate(c.b.d), "The copied date is still real 'Date' instance");
assert.notEqual(c.b.d, a.b.d, "And the copied date is not the same as the original");
assert.equal(c.b.d.getTime(), a.b.d.getTime(), "But the dates are the same");
assert.ok(isObject(c.b.d), "The copied date is now an object");
-Generated using TypeDoc
Generated using TypeDoc
Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil +
Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil for older browsers that do not define Object.create eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Object.create implementation if it exists as this would cause a testing requirement to test with and without the implementations
-Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil +
Creates an object that has the specified prototype, and that optionally contains specified properties. This helper exists to avoid adding a polyfil for older browsers that do not define Object.create eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Object.create implementation if it exists as this would cause a testing requirement to test with and without the implementations
-Generated using TypeDoc
Generated using TypeDoc
Performs a deep copy of the source object, this is designed to work with base (plain) objects, arrays and primitives +
Performs a deep copy of the source object, this is designed to work with base (plain) objects, arrays and primitives if the source object contains class objects they will either be not cloned or may be considered non-operational after performing a deep copy. ie. This is performing a deep copy of the objects properties so that altering the copy will not mutate the source object hierarchy. Automatic handling of recursive properties was added in v0.4.4.
-The source object to be copied
-Optional
handler: ObjDeepCopyHandlerAn optional callback that lets you provide / overide the deep cloning (Since 0.4.4)
+The source object to be copied
+Optional
handler: ObjDeepCopyHandlerAn optional callback that lets you provide / overide the deep cloning (Since 0.4.4)
A new object which contains a deep copy of the source properties
let a: any = { a: 1 };
let b: any = { b: 2, d: new Date(), e: new TestClass("Hello Darkness") };
a.b = b; // { a: 1, b: { b: 2} }
b.a = a; // { a: 1, b: { b: 2, a: { a: 1, { b: 2, a: ... }}}}
function copyHandler(details: IObjDeepCopyHandlerDetails) {
// details.origin === a
// details.path[] is the path to the current value
if (details.value && isDate(details.value)) {
// So for the date path === [ "b", "d" ] which represents
// details.origin["b"]["d"] === The Date
// Return true to indicate that we have "handled" the conversion
// Which in this case will reuse the existing instance (as we didn't replace details.value)
// See objCopyProps example for replacing the Date instance
return true;
}
return false;
}
let c: any = objDeepCopy(a, copyHandler);
assert.notEqual(a, c, "check a and c are not the same");
assert.ok(c === c.b.a, "The root object won't be the same for the target reference");
assert.ok(c.b === c.b.a.b, "Check that the 2 'b' references are the same object");
assert.ok(c.b.a === c.b.a.b.a, "Check that the 2 'a' references are the same object");
assert.ok(c.b.d === c.b.a.b.d, "Check that the 2 'd' references are the same object");
assert.ok(isDate(c.b.d), "The copied date is still real 'Date' instance");
assert.equal(c.b.d, a.b.d, "And the copied date is the original date");
assert.equal(c.b.d.getTime(), a.b.d.getTime(), "But the dates are the same");
assert.ok(isObject(c.b.d), "The copied date is now an object");
assert.ok(!isError(c.b.e), "The copied error is no longer a real 'Error' instance");
assert.ok(isObject(c.b.e), "The copied error is now an object");
assert.equal(42, c.b.e.value, "Expect that the local property was copied");
-Generated using TypeDoc
Generated using TypeDoc
Identifies the Symbol static properties which are symbols themselves as a constant +
- Preparing search index...
- The search index is not available
@nevware21/ts-utilsEnumeration WellKnownSymbols
Const
Identifies the Symbol static properties which are symbols themselves as a constant enum to aid in minification when fetching them from the global symbol implementation.
See: Well Known Symbols
-Index
Enumeration Members
Enumeration Members
async Iterator
The Symbol.asyncIterator symbol is a builtin symbol that is used to access an +
Index
Enumeration Members
Enumeration Members
async Iterator
The Symbol.asyncIterator symbol is a builtin symbol that is used to access an object's @@asyncIterator method. In order for an object to be async iterable, it must have a Symbol.asyncIterator key.
See: Symbol.asyncIterator
-has Instance
The Symbol.hasInstance well-known symbol is used to determine if a constructor +
has Instance
The Symbol.hasInstance well-known symbol is used to determine if a constructor object recognizes an object as its instance. The instanceof operator's behavior can be customized by this symbol.
See: Symbol.hasInstance
-is Concat Spreadable
The @@isConcatSpreadable symbol (Symbol.isConcatSpreadable) can be defined as an +
is Concat Spreadable
The @@isConcatSpreadable symbol (Symbol.isConcatSpreadable) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects:
@@ -32,51 +32,51 @@ Symbol.isConcatSpreadable can force flattening in these cases.
See: Symbol.isConcatSpreadable
-iterator
Whenever an object needs to be iterated (such as at the beginning of a for..of loop), +
iterator
Whenever an object needs to be iterated (such as at the beginning of a for..of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated.
See: Symbol.iterator
-match
This function is also used to identify if objects have the behavior of regular expressions. +
match
This function is also used to identify if objects have the behavior of regular expressions. For example, the methods String.prototype.startsWith(), String.prototype.endsWith() and String.prototype.includes(), check if their first argument is a regular expression and will throw a TypeError if they are. Now, if the match symbol is set to false (or a Falsy value), it indicates that the object is not intended to be used as a regular expression object.
See: Symbol.match
-match All
The Symbol.matchAll well-known symbol returns an iterator, that yields matches of the regular +
match All
The Symbol.matchAll well-known symbol returns an iterator, that yields matches of the regular expression against a string. This function is called by the String.prototype.matchAll() method.
See: Symbol.matchAll
-replace
The Symbol.replace well-known symbol specifies the method that replaces matched substrings +
replace
The Symbol.replace well-known symbol specifies the method that replaces matched substrings of a string. This function is called by the String.prototype.replace() method.
For more information, RegExp.prototype[@@replace]() and String.prototype.replace().
See: Symbol.replace
-search
The Symbol.search well-known symbol specifies the method that returns the index within a +
search
The Symbol.search well-known symbol specifies the method that returns the index within a string that matches the regular expression. This function is called by the String.prototype.search() method.
For more information, see RegExp.prototype[@@search]() and String.prototype.search().
See: Symbol.species
-species
The well-known symbol Symbol.species specifies a function-valued property that the constructor +
species
The well-known symbol Symbol.species specifies a function-valued property that the constructor function uses to create derived objects. See: Symbol.species
-split
The Symbol.split well-known symbol specifies the method that splits a string at the indices +
split
The Symbol.split well-known symbol specifies the method that splits a string at the indices that match a regular expression. This function is called by the String.prototype.split() method.
For more information, see RegExp.prototype[@@split]() and String.prototype.split(). See: Symbol.split
-to Primitive
With the help of the Symbol.toPrimitive property (used as a function value), an object can be +
to Primitive
With the help of the Symbol.toPrimitive property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint, which specifies the preferred type of the result primitive value. The hint argument can be one of "number", "string", and "default".
See: Symbol.toPrimitive
-to String Tag
The Symbol.toStringTag well-known symbol is a string valued property that is used in the +
to String Tag
The Symbol.toStringTag well-known symbol is a string valued property that is used in the creation of the default string description of an object. It is accessed internally by the Object.prototype.toString() method.
See: Symbol.toStringTag
-unscopables
The Symbol.unscopables well-known symbol is used to specify an object value of whose own +
unscopables
The Symbol.unscopables well-known symbol is used to specify an object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.
See: Symbol.unscopables
-Settings
Member Visibility
Theme
On This Page
Generated using TypeDoc