Array.uts 18.4 KB
Newer Older
Y
yurj26 已提交
1 2
import { describe, test, expect, Result } from './tests.uts'

3 4

            
Y
yurj26 已提交
5 6
export function testArray(): Result {
    return describe("Array", () => {
杜庆泉's avatar
杜庆泉 已提交
7 8 9 10 11 12 13 14
		
		test('constructor', () => {
			// 构造器测试
			let a1 = [1,2,3]
			expect(a1).toEqual([1,2,3]);
			let a2 = [1,'2',3]
			expect(a2).toEqual([1,'2',3]);
			let a3 = new Array(1,2,3);
lizhongyi_'s avatar
lizhongyi_ 已提交
15 16 17
		
		// swift 中字面量创建数组,仅支持同一类型的元素
		// #ifndef APP-IOS
杜庆泉's avatar
杜庆泉 已提交
18
			expect(a3).toEqual(new Array(1,2,3));
19 20
			let a4 = new Array<any>(1,'2',3);
			expect(a4).toEqual(new Array<any>(1,'2',3));
杜庆泉's avatar
杜庆泉 已提交
21 22
			let a5 = Array(1,2,3);
			expect(a5).toEqual(Array(1,2,3));
23 24
			let a6 = Array<any>(1,'2','3')
			expect(a6).toEqual(Array<any>(1,'2','3'));
lizhongyi_'s avatar
lizhongyi_ 已提交
25 26
		// #endif

杜庆泉's avatar
杜庆泉 已提交
27 28
		})
		
杜庆泉's avatar
杜庆泉 已提交
29 30 31 32 33 34
		test('equals', () => {
			// 构造器测试
			let a1 = [1,2,3]
			let a2 = [1,2,3]
			let equalsRet = (a1 == a2)
			console.log(equalsRet)
lizhongyi_'s avatar
lizhongyi_ 已提交
35 36 37 38 39 40 41
			// #ifndef APP-IOS
				expect(equalsRet).toEqual(false);
			// #endif
			// #ifdef APP-IOS
				expect(equalsRet).toEqual(true);
			// #endif
			
杜庆泉's avatar
杜庆泉 已提交
42 43 44
			
		})
		
Y
yurj26 已提交
45
        test('length', () => {
杜庆泉's avatar
杜庆泉 已提交
46
            const arr = ['shoes', 'shirts', 'socks', 'sweaters'];
Y
yurj26 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
            expect(arr.length).toEqual(4);
            expect(arr[0]).toEqual('shoes');
            expect(arr[1]).toEqual('shirts');
            // expect(arr[4]).toEqual(null);
            const numbers: number[] = [1, 2, 3, 4, 5];
            if (numbers.length > 3) {
              numbers.length = 3;
            }
            expect(numbers.length).toEqual(3);
            expect(numbers).toEqual([1, 2, 3]);
            expect([].length).toEqual(0);
            
            // 1. web: 最大长度 2^32-1
            // 超出边界报错: RangeError: Invalid array length
            // 2. kotlin: 最大长度 2^31-1
            // 超出边界报错: Error: targetMethod error::java.lang.OutOfMemoryError: Failed to allocate a 420546432 byte allocation with 6291456 free bytes and 300MB until OOM, target footprint 295113520, growth limit 603979776
            // 3. swift: 最大长度和内存有关
            // 超出边界没有返回信息
        })
        test("concat", () => {
            expect(['a', 'b', 'c'].concat(['d', 'e', 'f'])).toEqual(["a", "b", "c", "d", "e", "f"]);
            expect([1, 2, 3].concat([4, 5, 6])).toEqual([1, 2, 3, 4, 5, 6]);
            expect([''].concat([''])).toEqual(["", ""]);
杜庆泉's avatar
杜庆泉 已提交
70 71 72
            const num1 = [1, 2, 3];
            const num2 = [4, 5, 6];
            const num3 = [7, 8, 9];
Y
yurj26 已提交
73 74 75 76
            const numbers = num1.concat(num2, num3);
            expect(numbers).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
        })
        test("copyWithin", () => {
杜庆泉's avatar
杜庆泉 已提交
77
            const arr =  ['a', 'b', 'c', 'd', 'e'];
Y
yurj26 已提交
78 79
            expect(arr.copyWithin(0, 3, 4)).toEqual(["d", "b", "c", "d", "e"]);
            expect(arr.copyWithin(1, 3)).toEqual(["d", "d", "e", "d", "e"]);
杜庆泉's avatar
杜庆泉 已提交
80
            const arr2 = [1, 2, 3, 4, 5];
Y
yurj26 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            expect(arr2.copyWithin(-2)).toEqual([1, 2, 3, 1, 2]);
            expect(arr2.copyWithin(-2, -3, -1)).toEqual([1, 2, 3, 3, 1]);
        })
        test("every", () => {
            const isBelowThreshold = (currentValue:number):boolean=> currentValue < 40;
            const array1: number[] = [1, 30, 39, 29, 10, 13];
            const array2: number[] = [1, 30, 39, 29, 10, 13, 41];
            expect(array1.every(isBelowThreshold)).toEqual(true);
            expect(array2.every(isBelowThreshold)).toEqual(false);
            const array3: number[] = [1, 2, 3];
            array3.every((element:number, index:number, array:number[]):boolean => {
                expect(array[index]).toEqual(element);
                return true;
            })
        })
        test("fill", () => {
            const array1: number[] = [1, 2, 3, 4];
            expect(array1.fill(0, 2, 4)).toEqual([1, 2, 0, 0]);
            expect(array1.fill(5, 1)).toEqual([1, 5, 5, 5]);
            expect(array1.fill(6)).toEqual([6, 6, 6, 6]);
            const array2: number[]= [1, 2, 3]
            expect(array2.fill(4)).toEqual([4, 4, 4]);
            const array3: number[]= [0, 0]
            expect(array3.fill(1, null)).toEqual([1, 1]);
            expect(array3.fill(1, 0, 1.5)).toEqual([1, 1]);
        })
        test("filter", () => {
            const words: string[] = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
            const result = words.filter((word:string):boolean => word.length > 6);
            expect(result).toEqual(["exuberant", "destruction", "present"]);
            const array1: number[] = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
            const isPrime = array1.filter((num:number):boolean => {
                for (let i = 2; num > i; i++) {
                    // swift里,基础类型暂不支持!==,===对比
                    if (num % i == 0) {
                        return false;
                    }
                }
                return num > 1;
            })
            expect(isPrime).toEqual([2, 3, 5, 7, 11, 13]);
            const array2: number[] = [1, 2, 3];
            array2.filter((element:number, index:number, array:number[]):boolean => {
                expect(array[index]).toEqual(element);
                return true;
            })
        })
        test("find", () => {
            const array1: number[] = [5, 12, 8, 130, 44];
            const found1 = array1.find((element:number):boolean => element > 10);
            expect(found1).toEqual(12);
            const found2 = array1.find((element:number):boolean => element < 5);
            expect(found2).toEqual(null);
            const array2: number[] = [1, 2, 3];
            array2.find((element:number, index:number, array:number[]):boolean => {
                expect(array[index]).toEqual(element);
                return true;
            })
        })
        test("findIndex", () => {
            const array1: number[] = [5, 12, 8, 130, 44];
            const isLargeNumber = (element:number):boolean => element > 13;
            expect(array1.findIndex(isLargeNumber)).toEqual(3);
            const array2: number[] = [10, 11, 12];
            expect(array2.findIndex(isLargeNumber)).toEqual(-1);
            const array3: number[] = [1, 2, 3];
            array3.findIndex((element:number, index:number, array:number[]):boolean => {
                expect(array[index]).toEqual(element);
                return true;
            })
        })
        test("flat", () => {
            const arr1: any[] = [0, 1, 2, [3, 4]];
            expect(arr1.flat()).toEqual([0, 1, 2, 3, 4]);
            const arr2: any[] = [0, 1, 2, [[[3, 4]]]];
            expect(arr2.flat(2)).toEqual([0, 1, 2, [3, 4]]);
            const arr3: any[] = [1, 2, [3, 4, [5, 6]]];
            expect(arr3.flat(2)).toEqual([1, 2, 3, 4, 5, 6]);
        })
        test("forEach", () => {
            const array1: string[] = ['a', 'b', 'c'];
            array1.forEach((element:string, index:number) => {
                expect(array1[index]).toEqual(element)
            });
            
            const items: string[] = ['item1', 'item2', 'item3'];
            const copyItems: string[] = [];
            items.forEach((item:string) => {
              copyItems.push(item);
            });
            expect(copyItems).toEqual(items)
        })
        test("includes", () => {
            const array1: number[] = [1, 2, 3];
            expect(array1.includes(2)).toEqual(true);
            const pets: string[] = ['cat', 'dog', 'bat'];
            expect(pets.includes('cat')).toEqual(true);
            expect(pets.includes('at')).toEqual(false);
            const array2: string[] = ['a', 'b', 'c'];
            expect(array2.includes('c', 3)).toEqual(false);
            expect(array2.includes('c', 100)).toEqual(false);
182 183 184 185 186
            
            type P = {
              x : number
              y : number
            }
lizhongyi_'s avatar
lizhongyi_ 已提交
187 188 189 190
            // #ifndef APP-IOS
            	const s = JSON.parse<P[]>(JSON.stringify([{ x: 0, y: 0 }])) as P[]
            	s[0].x += 0;
            	const clearList = s.map((v : P, _, _a) : number => v.x)
191
            	expect(clearList.includes(0)).toEqual(true);
lizhongyi_'s avatar
lizhongyi_ 已提交
192 193 194 195 196 197 198 199
            // #endif
            // #ifdef APP-IOS
            	const s = JSON.parse<P[]>(JSON.stringify([{ x: 0, y: 0 }])!) as P[]
            	s[0].x += 0;
            	const clearList = s.map((v : P, index: number, _a) : number => v.x)
            	expect(clearList.includes(0)).toEqual(true);
            // #endif
 
Y
yurj26 已提交
200 201
        })
        test("indexOf", () => {
杜庆泉's avatar
杜庆泉 已提交
202 203
			
			let raw = {}
lizhongyi_'s avatar
lizhongyi_ 已提交
204
			let arr = new Array<UTSJSONObject>()
杜庆泉's avatar
杜庆泉 已提交
205 206 207 208 209
			arr.push({});
			arr.push({});
			arr.push(raw);
			expect(arr.indexOf(raw)).toEqual(2);
			
Y
yurj26 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            const beasts: string[] = ['ant', 'bison', 'camel', 'duck', 'bison'];
            expect(beasts.indexOf('bison')).toEqual(1);
            expect(beasts.indexOf('bison', 2)).toEqual(4);
            expect(beasts.indexOf('giraffe')).toEqual(-1);
            
            const indices: number[] = [];
            const array: string[] = ['a', 'b', 'a', 'c', 'a', 'd'];
            const element = 'a';
            let idx = array.indexOf(element);
            // swift里,基础类型暂不支持!==,===对比
            while (idx != -1) {
              indices.push(idx);
              idx = array.indexOf(element, idx + 1);
            }
            expect(indices).toEqual([0, 2, 4]);
        })
        test("join", () => {
            const elements: string[] = ['Fire', 'Air', 'Water'];
            expect(elements.join()).toEqual("Fire,Air,Water");
            expect(elements.join('')).toEqual("FireAirWater");
            expect(elements.join('-')).toEqual("Fire-Air-Water");
        })
        test("lastIndexOf", () => {
杜庆泉's avatar
杜庆泉 已提交
233 234
			
			let raw = {}
lizhongyi_'s avatar
lizhongyi_ 已提交
235
			let arr = new Array<UTSJSONObject>()
杜庆泉's avatar
杜庆泉 已提交
236 237 238 239 240 241
			arr.push({});
			arr.push({});
			arr.push(raw);
			expect(arr.lastIndexOf(raw)).toEqual(2);
			
			
Y
yurj26 已提交
242 243 244 245 246 247 248 249 250 251 252 253
            const animals: string[] = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
            expect(animals.lastIndexOf('Dodo')).toEqual(3);
            expect(animals.lastIndexOf('Tiger')).toEqual(1);
            const array: number[] = [2, 5, 9, 2];
            let index = array.lastIndexOf(2);
            expect(index).toEqual(3);
            index = array.lastIndexOf(7);
            expect(index).toEqual(-1);
            index = array.lastIndexOf(2, 3);
            expect(index).toEqual(3);
            index = array.lastIndexOf(2, 2);
            expect(index).toEqual(0);
杜庆泉's avatar
杜庆泉 已提交
254 255 256 257
			
			
			
			
Y
yurj26 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        })
        test("map", () => {
            const array1: number[] = [1, 4, 9, 16];
            const map1 = array1.map((x:number):number => x * 2);
            expect(map1).toEqual([2, 8, 18, 32]);
            
            const numbers: number[] = [1, 4, 9];
            const roots = numbers.map((num:number):number => num + 1);
            expect(numbers).toEqual([1, 4, 9]);
            expect(roots).toEqual([2, 5, 10]);
            
            const array2: number[] = [1, 2, 3];
            array2.map((element:number, index:number, array:number[]) => {
                expect(array[index]).toEqual(element);
            })
        })
        test("pop", () => {
            const plants: string[] = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
            expect(plants.pop()).toEqual("tomato");
            expect(plants).toEqual(["broccoli", "cauliflower", "cabbage", "kale"]);
            plants.pop();
            expect(plants).toEqual(["broccoli", "cauliflower", "cabbage"]);
        })
        test("push", () => {
            const animals: string[] = ['pigs', 'goats', 'sheep'];
            const count = animals.push('cows');
            expect(count).toEqual(4);
            expect(animals).toEqual(['pigs', 'goats', 'sheep', 'cows']);
            animals.push('chickens', 'cats', 'dogs');
            expect(animals).toEqual(["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]);
        })
        test("reduce", () => {
            const array1: number[] = [1, 2, 3, 4];
            const initialValue:number = 0;
            const sumWithInitial = array1.reduce(
              (previousValue:number, currentValue:number):number => previousValue + currentValue,
              initialValue
            );
            expect(sumWithInitial).toEqual(10);
        })
        test("shift", () => {
            const array1: number[] =  [1, 2, 3];
            const firstElement = array1.shift();
            expect(firstElement).toEqual(1);
            expect(array1).toEqual([2, 3]);
        })
        test("slice", () => {
            const animals: string[] = ['ant', 'bison', 'camel', 'duck', 'elephant'];
            expect(animals.slice(2)).toEqual(["camel", "duck", "elephant"]);
            expect(animals.slice(2, 4)).toEqual(["camel", "duck"]);
            expect(animals.slice(1, 5)).toEqual(["bison", "camel", "duck", "elephant"]);
            expect(animals.slice(-2)).toEqual(["duck", "elephant"]);
            expect(animals.slice(2, -1)).toEqual(["camel", "duck"]);
            expect(animals.slice()).toEqual(["ant", "bison", "camel", "duck", "elephant"]);
        })
        test("some", () => {
            const array: number[] = [1, 2, 3, 4, 5];
            const even = (element:number):boolean=> element % 2 == 0;
            expect(array.some(even)).toEqual(true);
            const isBiggerThan10 = (element:number):boolean=> element > 10;
            expect([2, 5, 8, 1, 4].some(isBiggerThan10)).toEqual(false);
            expect([12, 5, 8, 1, 4].some(isBiggerThan10)).toEqual(true);
        })
        test("splice", () => {
            const months: string[] = ['Jan', 'March', 'April', 'June'];
            months.splice(1, 0, 'Feb');
            expect(months).toEqual(["Jan", "Feb", "March", "April", "June"]);
            months.splice(4, 1, 'May');
            expect(months).toEqual(["Jan", "Feb", "March", "April", "May"]);
        })
        test('sort', () => {
            const months = ['March', 'Jan', 'Feb', 'Dec'];
            months.sort();
            expect(months).toEqual(["Dec", "Feb", "Jan", "March"]);
            
            const array1 = [1, 30, 4, 21, 100000];
            array1.sort();
            expect(array1).toEqual([1, 100000, 21, 30, 4]);
            
            const array2 = [5, 1, 4, 2, 3];
杜庆泉's avatar
杜庆泉 已提交
338
            array2.sort((a, b):number => a - b);
Y
yurj26 已提交
339 340 341 342 343 344 345 346 347 348
            expect(array2).toEqual([1, 2, 3, 4, 5]);
            
            // const array3 = [5, "banana", 4, "apple", 3, "cherry", 2, "date", 1];
            // array3.sort();
            // expect(array3).toEqual([1, 2, 3, 4, 5, "apple", "banana", "cherry", "date"]);
            
            const array4 = [
              { name: "John", age: 24 },
              { name: "Sarah", age: 19 },
              { name: "Bob", age: 27 },
lizhongyi_'s avatar
lizhongyi_ 已提交
349
              { name: "Alice", age: 21 }   
Y
yurj26 已提交
350 351 352
            ];
            // 先强转类型,解决编译报错
            array4.sort((a, b):number => (a['age'] as number) - (b['age'] as number));
lizhongyi_'s avatar
lizhongyi_ 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365
			
			// #ifndef APP-IOS
				expect(array4).toEqual([{ name: "Sarah", age: 19 }, { name: "Alice", age: 21 }, { name: "John", age: 24 }, { name: "Bob", age: 27 }]);
			// #endif
			
			// #ifdef APP-IOS
				const arr = array4.map((value: UTSJSONObject): number => { return value["age"] as number })
				expect(arr).toEqual([19, 21, 24, 27])
			// #endif
			
            
			

Y
yurj26 已提交
366 367 368 369 370 371
        })
        test("unshift", () => {
            const array1: number[] = [1, 2, 3];
            expect(array1.unshift(4, 5)).toEqual(5);
            expect(array1).toEqual([4, 5, 1, 2, 3]);
        })
杜庆泉's avatar
杜庆泉 已提交
372 373 374 375 376 377 378 379 380
		test("toString", () => {
		    const array1: number[] = [1, 2, 3];
		    expect(array1.toString()).toEqual("1,2,3");
			const array2 = new Array<string>()
			array2.push("a")
			array2.push("b")
			array2.push("c")
			expect(array2.toString()).toEqual("a,b,c");
		})
Y
yurj26 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
        test('reverse', () => {
            // const array1: string[] = ['one', 'two', 'three'];
            // const reversed1: string[] = array1.reverse();
            // expect(reversed1).toEqual(["three", "two", "one"]);
            // expect(array1).toEqual(["three", "·two", "one"]);
            
            // const array2 = [1, 2, 3, 4, 5];
            // const reversed2 = array2.reverse();
            // expect(reversed2).toEqual([5, 4, 3, 2, 1]);
            // expect(array2).toEqual([5, 4, 3, 2, 1]);
        })
        test("reduceRight", () => {
            const array1: number[][] = [[0, 1], [2, 3], [4, 5]];
            const result1 = array1.reduceRight((accumulator: number[], currentValue: number[]): number[] => accumulator.concat(currentValue));
            expect(result1).toEqual([4, 5, 2, 3, 0, 1]);
            
            const array2: number[] = [1, 2, 3, 4];
            const result2 = array2.reduceRight((acc: number, cur: number, index: number, array: number[]): number => {
                expect(array[index]).toEqual(cur);
                return acc + cur;
            });
            expect(result2).toEqual(10);
            
            const result3 = array2.reduceRight((acc: number, cur: number): number => acc + cur, 5);
            expect(result3).toEqual(15);
        })
        test("flatMap", () => {
            const arr: number[] = [1, 2, 3];
            const result = arr.flatMap((x: number):number[] => [x, x * 2]);
            expect(result).toEqual([1, 2, 2, 4, 3, 6]);
            
            const arr1: number[] = [1, 2, 3, 4];
            const result1 = arr1.flatMap((num: number, index: number, array: number[]): number[] => {
                expect(array[index]).toEqual(num);
                if (num % 2 == 0) {
                    return [num * 2];
                }
                return [];
            });
            expect(result1).toEqual([4, 8]);
        })
        test("entries", () => {
            // const array1 = ['a', 'b', 'c'];
            // const iterator1 = array1.entries();
            // expect(iterator1.next().value).toEqual([0, "a"]);
            // expect(iterator1.next().value).toEqual([1, "b"]);
            // expect(iterator1.next().value).toEqual([2, "c"]);
            // expect(iterator1.next().done).toEqual(true);
            
            // const array2: any[] = [1, 2, 'hello', true, { name: 'john', age: 30 }, [4, 5]];
            // let count = 0;
            // for (const [index, element] of array2.entries()) {
            //     count++;
            //     expect(element).toEqual(array2[index]);
            // }
            // expect(count).toEqual(array2.length);
        })
        test("keys", () => {
            // const array1 = ['a', 'b', 'c'];
            // const iterator1 = array1.keys();
            // expect(iterator1.next().value).toEqual(0);
            // expect(iterator1.next().value).toEqual(1);
            // expect(iterator1.next().value).toEqual(2);
            // expect(iterator1.next().done).toEqual(true);
        })
杜庆泉's avatar
杜庆泉 已提交
446
		
Y
yurj26 已提交
447 448
    })
}