1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import * as crypto from 'crypto'; 17 18export class ListUtil { 19 public static readonly MAX_INIT_LEN: number = 0xFFFF; 20 21 /** 22 * get a list with element number filled for each element 23 * @param length: list length you want init. 24 */ 25 public static getInitList(length: number): number[] { 26 if (isNaN(length) || length < 0 || length > this.MAX_INIT_LEN) { 27 console.error(`array init length is invalid, should in range: [0, ${this.MAX_INIT_LEN}]`); 28 return []; 29 } 30 31 return Array(length).fill(null).map((_, h) => h); 32 } 33 34 /** 35 * shuffle list 36 * @param originList: list to be shuffled 37 */ 38 public static shuffle(originList: number[]): void { 39 if (!originList) { 40 return; 41 } 42 43 for (let i = originList.length; i > 0; i--) { 44 let j = crypto.randomInt(originList.length); 45 [originList[i - 1], originList[j]] = [originList[j], originList[i - 1]]; 46 } 47 } 48 49 /** 50 * merge two list to one list of unique element 51 * @param listA 52 * @param listB 53 * @param listC 54 */ 55 public static uniqueMergeList(listA: string[], listB: string[], listC?: string[]): string[] { 56 const firstList: string[] = listA ? listA : []; 57 const secondList: string[] = listB ? listB : []; 58 const thirdList: string[] = listC ? listC : []; 59 60 const tmpList: string[] = thirdList ? [...firstList, ...secondList, ...thirdList] : [...firstList, ...secondList]; 61 const elementSet: Set<string> = new Set<string>(tmpList); 62 return Array.from(elementSet); 63 } 64} 65