73 lines
1.9 KiB
TypeScript
Raw Normal View History

/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Equivalent to ES6 spread, add each item to an array.
*
* @param items The items to add
* @param arr The array to which you want to add the items
*/
export function addAllToArray(items: any[], arr: any[]) {
for (let i = 0; i < items.length; i++) {
arr.push(items[i]);
}
}
/**
* Flattens an array.
*/
export function flatten(list: any[], dst?: any[]): any[] {
if (dst === undefined) dst = list;
for (let i = 0; i < list.length; i++) {
let item = list[i];
if (Array.isArray(item)) {
// we need to inline it.
if (dst === list) {
// Our assumption that the list was already flat was wrong and
// we need to clone flat since we need to write to it.
dst = list.slice(0, i);
}
flatten(item, dst);
} else if (dst !== list) {
dst.push(item);
}
}
return dst;
}
export function deepForEach<T>(input: (T | any[])[], fn: (value: T) => void): void {
input.forEach(value => Array.isArray(value) ? deepForEach(value, fn) : fn(value));
}
export function addToArray(arr: any[], index: number, value: any): void {
// perf: array.push is faster than array.splice!
if (index >= arr.length) {
arr.push(value);
} else {
arr.splice(index, 0, value);
}
}
export function removeFromArray(arr: any[], index: number): any {
// perf: array.pop is faster than array.splice!
if (index >= arr.length - 1) {
return arr.pop();
} else {
return arr.splice(index, 1)[0];
}
}
export function newArray<T = any>(size: number): T[];
export function newArray<T>(size: number, value: T): T[];
export function newArray<T>(size: number, value?: T): T[] {
const list: T[] = [];
for (let i = 0; i < size; i++) {
list.push(value !);
}
return list;
}