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 16const array1 = [1, 2, 3, 4]; 17const initialValue = 0; 18const sumWithInitial = array1.reduce( 19 (accumulator, currentValue) => accumulator + currentValue, 20 initialValue, 21); 22print(sumWithInitial); 23const objects = [{ x: 1 }, { x: 2 }, { x: 3 }]; 24const sum = objects.reduce( 25 (accumulator, currentValue) => accumulator + currentValue.x, 26 0, 27); 28print(sum); // 6 29print([1, 2, , 4].reduce((a, b) => a + b)); // 7 30print([1, 2, undefined, 4].reduce((a, b) => a + b)); // NaN 31const arrayLike = { 32 length: 3, 33 0: 2, 34 1: 3, 35 2: 4, 36}; 37print(Array.prototype.reduce.call(arrayLike, (x, y) => x + y)); 38const myArray = ["a", "b", "a", "b", "c", "e", "e", "c", "d", "d", "d", "d"]; 39const myArrayWithNoDuplicates = myArray.reduce((accumulator, currentValue) => { 40 if (!accumulator.includes(currentValue)) { 41 return [...accumulator, currentValue]; 42 } 43 return accumulator; 44}, []); 45 46print(myArrayWithNoDuplicates); 47const numbers = [-5, 6, 2, 0]; 48 49const doubledPositiveNumbers = numbers.reduce((accumulator, currentValue) => { 50 if (currentValue > 0) { 51 const doubled = currentValue * 2; 52 return [...accumulator, doubled]; 53 } 54 return accumulator; 55}, []); 56 57print(doubledPositiveNumbers); // [12, 4] 58 59function runPromiseInSequence(arr, input) { 60 return arr.reduce( 61 (promiseChain, currentFunction) => promiseChain.then(currentFunction), 62 Promise.resolve(input), 63 ); 64} 65 66function p1(a) { 67 return new Promise((resolve, reject) => { 68 resolve(a * 5); 69 }); 70} 71 72function p2(a) { 73 return new Promise((resolve, reject) => { 74 resolve(a * 2); 75 }); 76} 77 78function f3(a) { 79 return a * 3; 80} 81 82function p4(a) { 83 return new Promise((resolve, reject) => { 84 resolve(a * 4); 85 }); 86} 87 88const promiseArr = [p1, p2, f3, p4]; 89runPromiseInSequence(promiseArr, 10).then(console.log); // 1200 90