2017-10-12 00:01:37 +03:00
|
|
|
/**
|
|
|
|
* Maps over array passing `isLast` bool to iterator as the second arguemnt
|
|
|
|
*/
|
|
|
|
export function mapWithLast<T, P>(array: T[], iteratee: (item: T, isLast: boolean) => P) {
|
|
|
|
const res: P[] = [];
|
|
|
|
for (let i = 0; i < array.length - 1; i++) {
|
|
|
|
res.push(iteratee(array[i], false));
|
|
|
|
}
|
|
|
|
if (array.length !== 0) {
|
|
|
|
res.push(iteratee(array[array.length - 1], true));
|
|
|
|
}
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates an object with the same keys as object and values generated by running each
|
|
|
|
* own enumerable string keyed property of object thru iteratee.
|
|
|
|
* The iteratee is invoked with three arguments: (value, key, object).
|
|
|
|
*
|
|
|
|
* @param object the object to iterate over
|
|
|
|
* @param iteratee the function invoked per iteration.
|
|
|
|
*/
|
|
|
|
export function mapValues<T, P>(
|
|
|
|
object: Dict<T>,
|
|
|
|
iteratee: (val: T, key: string, obj: Dict<T>) => P,
|
|
|
|
): Dict<P> {
|
|
|
|
const res: { [key: string]: P } = {};
|
|
|
|
for (let key in object) {
|
|
|
|
if (object.hasOwnProperty(key)) {
|
|
|
|
res[key] = iteratee(object[key], key, object);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* flattens collection using `prop` field as a children
|
|
|
|
* @param items collection items
|
|
|
|
* @param prop item property with child elements
|
|
|
|
*/
|
|
|
|
export function flattenByProp<T extends object, P extends keyof T>(items: T[], prop: P): T[] {
|
|
|
|
const res: T[] = [];
|
|
|
|
const iterate = (items: T[]) => {
|
|
|
|
for (let i = 0; i < items.length; i++) {
|
|
|
|
const item = items[i];
|
|
|
|
res.push(item);
|
|
|
|
if (item[prop]) {
|
|
|
|
iterate(item[prop]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
iterate(items);
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function stripTrailingSlash(path: string): string {
|
|
|
|
if (path.endsWith('/')) {
|
|
|
|
return path.substring(0, path.length - 1);
|
|
|
|
}
|
|
|
|
return path;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function isAbsolutePath(path: string): boolean {
|
|
|
|
return /^(?:[a-z]+:)?/i.test(path);
|
|
|
|
}
|
2017-11-20 19:02:49 +03:00
|
|
|
|
|
|
|
export function isNumeric(n: any): n is Number {
|
|
|
|
return !isNaN(parseFloat(n)) && isFinite(n);
|
|
|
|
}
|