Algorithm: No.1 两数之和

  1. /**
  2. * Given nums = [2, 7, 11, 15], target = 9,
  3. * Because nums[0] + nums[1] = 2 + 7 = 9,
  4. * return [0, 1].
  5. * @author kanelogger
  6. * @result runtime 108ms ; memory 34.7 MB
  7. */
  8. var twoSum = function(nums, target) {
  9. for(let i = 0,l = nums.length;i<l;i++){
  10. for(let j = i+1;j<l;j++){
  11. if(nums[i]+nums[j] == target)return[i,j]
  12. }
  13. }
  14. };

One of the best answers in discussions

  1. /**
  2. * @result runtime 52ms ; memory 34.6MB
  3. */
  4. var twoSum = function(nums, target) {
  5. if (nums.length === 2) return [0, 1];
  6. const len = nums.length;
  7. let map = {};
  8. for(let i = 0; i < len; i++) {
  9. let n = target - nums[i];
  10. let find = map[n];
  11. if(find !== undefined) return [find, i];
  12. else map[nums[i]] = i;
  13. }
  14. };

只遍历一次数组,每一步都会将target与当前nums[i]进行对比,如果map中有对应的,则返回值与当前项索引,没有则将作为key,索引为value存入map.

胡思乱想 [9,8,7,6,5] key与value对调。

  1. function c(arr){
  2. let obj = {}
  3. for(let i =0;i<arr.length;i++){
  4. obj[arr[i]] = i
  5. }
  6. return obj
  7. }
  8. console.log(c(arr))

Review: 阅读并点评一篇英文技术文章

原文地址: When a Filter Goes Wrong: Adventures in Async/Await

作者通过六段代码向我们展示了filter在处理异步时是如何失效的,以及对应的解决办法。

常规用法 例子: 取数组偶数

  1. // normal
  2. const arr = [1,2,1,2];
  3. const results = arr.filter(v=> v%2 == 0);
  4. // expected output [2, 2]

嵌套函数

  1. // normal
  2. const double = v => v%2;
  3. const arr = [1,2,1,2];
  4. const results = arr.filter( v=> double(v) == 0);
  5. // expected output [2,2]

嵌套异步函数

  1. const double = v =>{
  2. return new Promise(resolve=>{
  3. setTimeout(()=>{
  4. resolve(v%2)
  5. },1000)
  6. })
  7. }
  8. const arr = [1,2,1,2];
  9. const results = arr.filter( v=> double(v) == 0);
  10. // inexpected output []

作者告诉我们,使用类似的异步方法,结果是一样的,调用函数不能返回给我们想要的结果。原因是输出在运行完成之前。即使filter 已经返回,异步操作仍在触发。

使用 async/await

  1. const double = v =>{
  2. return new Promise(resolve=>{
  3. setTimeout(()=>{
  4. resolve(v%2)
  5. },1000)
  6. })
  7. }
  8. const arr = [1,2,1,2];
  9. const results = arr.filter( async v => await double(v) == 0);
  10. // inexpected output [1, 2, 1, 2]

输出的是我们完整的原始数组。延时依然存在,平常我们都假定 async/await会在promise执行有结果的时候再处理结果。
经过大量的搜索,确认filter天然不支持async/await。在filter函数体外增加await这个方案也是不行的。
最后作者得出了一个不怎么优雅的解决方案。

  1. const double = v =>{
  2. return new Promise(resolve=>{
  3. setTimeout(()=>{
  4. resolve(v%2)
  5. },1000)
  6. })
  7. }
  8. const arr = [1,2,1,2];
  9. const results = [];
  10. const job = async () => {
  11. for (let value of arr) {
  12. if ((await double(value)) == 0) {
  13. results.push(value);
  14. }
  15. }
  16. }
  17. job().then(() => {
  18. console.log(results);
  19. });
  20. // expected output [2,2]

最后作者对await失效的原因还是很费解。me too!

Tips: 学习一个技术技巧

使用拓展运算符合并对象和对象数组

  1. // 合并对象
  2. const p1 = { name: 'zhangsan', age: 18 }
  3. const p2 = { name: 'lisi', address: 'the west lake' }
  4. const p = { ...p1, ...p2 };
  5. console.log(p); // {name: "lisi", age: 18, address: "the west lake"}
  6. // merging an array of objects into one
  7. const cities = [
  8. { name: 'Paris', visited: 'no' },
  9. { name: 'Lyon', visited: 'no' }
  10. ];
  11. const result = cities.reduce((pre, item) => {
  12. return {
  13. ...pre,
  14. [item.name]: item.visited
  15. }
  16. }, {});
  17. console.log(result);
  18. /* outputs
  19. Berlin: "no"
  20. Genoa: "yes"
  21. */

解构原始数据

  1. const originData = {
  2. name: "zhangsan",
  3. nickName: "dege",
  4. email: "nozuorenJoJo@dio.com",
  5. avatar:"image-path.webp",
  6. followers: 100,
  7. following: 1024
  8. }
  9. let dataMain = {}, dataDetail = {};
  10. ({ name: dataMain.name,nickName: dataMain.nickName,...dataDetail } = originData);
  11. console.log(dataMain) // {name: "zhangsan", nickName: "dege"}
  12. console.log(dataDetail) // {email: "nozuorenJoJo@dio.com", avatar: "image-path.webp", followers: 100, following: 1024}

带条件的对象属性

  1. const getUser = sign => {
  2. return {
  3. name:"zhangsan",
  4. age: 18,
  5. ...(sign? { isSB:sign } :null)
  6. }
  7. }
  8. const u = getUser(true)
  9. console.log(u) // {name: "zhangsan", age: 18, isSB: true}

Share: 分享一篇有观点和思考的技术文章

详解三次握手和四次挥手:遇到心动的女孩时,如何去把握?