const invertTree = function (root) {
if (!root) {
return
}
[root.left, root.right] = [root?.right, root?.left]
invertTree(root.left)
invertTree(root.right)
return root
}
const ensure = (output, expect, message) => {
if (JSON.stringify(output) === JSON.stringify(expect)) {
console.log(`${message} ok`)
} else {
console.log(`${message} fail`)
}
}
const test = function () {
const input = {
val: 1,
left: {
val: 2,
left: {
val: 3,
left: null,
right: null,
},
right: {
val: 4,
left: null,
right: null,
},
},
right: {
val: 5,
left: {
val: 6,
left: null,
right: null,
},
right: {
val: 7,
left: null,
right: null,
},
}
}
const expect = {
val: 1,
left: {
val: 5,
left: {
val: 7,
left: null,
right: null,
},
right: {
val: 6,
left: null,
right: null,
},
},
right: {
val: 2,
left: {
val: 4,
left: null,
right: null,
},
right: {
val: 3,
left: null,
right: null,
},
}
}
const output = invertTree(input)
ensure(output, expect, 'test')
}
test()
Promise._all = function (promises) {
return new Promise((r, j) => {
const result = []
promises.forEach((pro, index) => {
Promise.resolve(pro).then(res => {
result[index] = res
if ( index === promises.length-1) {
r(result)
}
}).catch(err => {
j(err)
})
})
})
}
const ensure = function (output, expect, message) {
if (JSON.stringify(output) === JSON.stringify(expect)) {
console.log(`${message} ok`)
} else {
console.log(`${message} error`)
}
}
const test1 = function () {
Promise.all([
new Promise(function (resolve, reject) {
setTimeout(() => {
resolve(1);
}, 2000);
}),
Promise.resolve(2),
3,
Promise.resolve(4),
]).then(l => {
console.log(l, 'lllll')
let r = [1, 2, 3, 4]
ensure(l, r, 'test 1')
}).catch(err => {
console.log(err)
})
}
const test2 = function () {
Promise._all([
Promise.reject('error 1'),
]).catch(err => {
ensure(err, 'error 1', 'test 2')
})
}
const test = function () {
test1()
test2()
}
test()