记一次面试题

本贴最后更新于 1985 天前,其中的信息可能已经时移世易

从事前端开发一年半,下面是我做的一份面试题,分享一下,
希望大家指出我实现过程中的不足。

/**

extensions is an Array and each item has such format:

{firstName: 'xxx', lastName: 'xxx', ext: 'xxx', extType: 'xxx'}

lastName, ext can be empty, extType can only has "DigitalUser", "VirtualUser","FaxUser","Dept","AO".

**/

  

/**

Question 1: sort extensions by "firstName" + "lastName" + "ext" ASC

**/

function sortExtensionsByName(extensions) {

    // reserved the type of sort

    let type = String(arguments[1]).toLowerCase() ===  'desc'  ?  'desc'  :  'asc';

  

    if (Array.isArray(extensions)) {

        extensions.sort(function(a, b) {

            let firstLength = Math.max(a.firstName.length, b.firstName.length),

                 lastLength = Math.max((a.lastName ||  '').length, (b.lastName ||  '').length),

                 extLength = Math.max((a.ext ||  '').length, (b.ext ||  '').length),

                 aStr,

                 bStr;

  

          aStr = a.firstName.padEnd(firstLength, ' ') + (a.lastName ||  '').padEnd(lastLength, ' ') + (a.ext ||  '').padEnd(extLength, ' '),

bStr = b.firstName.padEnd(firstLength, ' ') + (b.lastName ||  '').padEnd(lastLength, ' ') + (b.ext ||  '').padEnd(extLength, ' ');

return type ===  'asc'  ? aStr.localeCompare(bStr) : bStr.localeCompare(aStr);

          });

    } else {

        console.log("error: The first parameter should be an Array, e.g., [{firstName: 'xxx', lastName: 'xxx', ext: 'xxx', extType: 'xxx'}]");

    }

}

  
  

/**

Question 2: sort extensions by extType follow these orders ASC

DigitalUser < VirtualUser < FaxUser < AO < Dept.

**/

function sortExtensionsByExtType(extensions) {

    // reserved the type of sort

    let type = String(arguments[1]).toLowerCase() ===  'desc'  ?  'desc'  :  'asc',

         sortObj = {

             'Dept': 0,

             'AO': 1,

             'FaxUser': 2,

             'VirtualUser': 3,

             'DigitalUser': 4

         };

    if (Array.isArray(extensions)) {

        extensions.sort(function(a, b) {

            let aNum = sortObj[a.extType],

                 bNum = sortObj[b.extType];

            return type ===  'asc'  ? aNum - bNum : bNum - aNum;

        });

    } else {

        console.log("error: The first parameter should be an Array, e.g., [{firstName: 'xxx', lastName: 'xxx', ext: 'xxx', extType: 'xxx'}]");

    }

}

  
  

/**

saleItems is an Array has each item has such format:

{

  month: n, //[1-12],

  date: n, //[1-31],

  transationId: "xxx",

  salePrice: number

}

**/

  

/**

Question 3: write a function to calculate and return a list of total sales (sum) for each quarter, expected result like:

[

  {quarter: 1, totalPrices: xxx, transactionNums: n},

  {....}

]

**/

  

function sumByQuarter(saleItems) {

    let list = [

        {quarter: 1, totalPrices: 0, transactionNums: 0},

        {quarter: 2, totalPrices: 0, transactionNums: 0},

        {quarter: 3, totalPrices: 0, transactionNums: 0},

        {quarter: 4, totalPrices: 0, transactionNums: 0}

    ];

    if (Array.isArray(saleItems)) {

        saleItems.forEach(function(item) {

            let totalItem = {},

                 num = item.salePrice,

                 totalNum =  0,

                 baseNum1 =  0,

                 baseNum2 =  0,

                 baseNum =  0;

  

            if(item.month <  4) {

                totalItem = list[0];

            } else  if (item.month <  7) {

                totalItem = list[1];

            } else  if (item.month <  10) {

                totalItem = list[2];

            } else {

                totalItem = list[3];

            }

  

            totalItem.transactionNums++;

            totalNum = totalItem.totalPrices;

            // precision handling

            try {

                 baseNum1 = num.toString().split(".")[1].length;

            } catch (e) {

                 baseNum1 =  0;

            }

            try {

                baseNum2 = totalNum.toString().split(".")[1].length;

           } catch (e) {

                baseNum2 =  0;

            }

            baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));

  

            totalItem.totalPrices = (num * baseNum + totalNum * baseNum) / baseNum;

        });

    } else {

        console.log(`

            error: The first parameter should be an Array, e.g.,

            [

              {

                   month: n, //[1-12],

                   date: n, //[1-31],

                   transationId: "xxx",

                   salePrice: number

              }

          ]

       `);

    }

    return list;

}

  

/**

Question 4: write a function to calculate and return a list of average sales for each quarter, expected result like:

[

{quarter: 1, averagePrices: xxx, transactionNums: n},

{....}

]

**/

  

function averageByQuarter(saleItems) {

    // reused the 'sumByQuarter'

    let list = sumByQuarter(saleItems);

  

    list.forEach(function(item) {

        let num = item.totalPrices,

             totalNum = item.transactionNums,

             baseNum =  0;

        if(totalNum ===  0) {

            item.averagePrices =  0;

        } else {

            // precision handling

            try {

                baseNum = num.toString().split(".")[1].length;

            } catch (e) {

                baseNum =  0;

            }

            item.averagePrices = (Number(num.toString().replace(".", "")) / totalNum) / Math.pow(10, baseNum);

       }

        delete item.totalPrices;

    });

    return list;

}

  
  

/**

Question 5: please create a tool to generate Sequence

Expected to be used like:

var sequence1 = new Sequence();

sequence1.next() --> return 1;

sequence1.next() --> return 2;

in another module:

var sequence2 = new Sequence();

sequence2.next() --> 3;

sequence2.next() --> 4;

**/

  

// ES5

var Sequence;

(function(){

    var unique;

    Sequence =  function(){

        if(unique){

            return unique

        }

        unique =  this;

        this.index =  1;

        this.next =  function() {

           return  this.index++;

       };

    }

}());

  

// ES6

class Sequence {

    next() {

        return Sequence.index++;

    }

}

Sequence.index =  1;

  
  

/**

Question 6:

AllKeys: 0-9;

usedKeys: an array to store all used keys like [2,3,4];

We want to get an array which contains all the unused keys,in this example it would be: [0,1,5,6,7,8,9]

**/

  

function getUnUsedKeys(allKeys, usedKeys) {

    //TODO

    if (Array.isArray(allKeys) && Array.isArray(usedKeys)) {

        let newArr = allKeys.concat(usedKeys),

             unusedKeys = [];

  

        // sort the values, and then remove duplicate values in loop

       newArr.sort();

       for(let i =  0; i < newArr.length; i++){

           if(newArr[i] !== newArr[i+1]) {

                unusedKeys.push(newArr[i]);

           } else {

               i++;

           }

        }

        return unusedKeys;

    } else {

        console.log('error: The first parameter and the second parameter should be an Array');

    }

}
  • 代码
    460 引用 • 591 回帖 • 8 关注
  • 面试

    面试造航母,上班拧螺丝。多面试,少加班。

    324 引用 • 1395 回帖 • 1 关注

相关帖子

13 回帖

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • huazhi
    作者

    sumByQuarter,这个我也觉得精度处理的不好,不是的数据精度是怎么样的,在业务实践中,都是和后端沟通一下,直接放大/缩小 1000 就好了

    2 回复
  • 其他回帖
  • visus

    这个世界上,最帅的人就是自信的人

  • visus

    可以,这操作,拼多多,估计就是这 bug

  • visus

    👍 此处不留爷,自有留爷处,相信自己,除非别人给出信服理由,否者就这样干下去

  • 查看全部回帖

推荐标签 标签

  • 单点登录

    单点登录(Single Sign On)是目前比较流行的企业业务整合的解决方案之一。SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

    9 引用 • 25 回帖 • 2 关注
  • FFmpeg

    FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

    23 引用 • 31 回帖 • 8 关注
  • ReactiveX

    ReactiveX 是一个专注于异步编程与控制可观察数据(或者事件)流的 API。它组合了观察者模式,迭代器模式和函数式编程的优秀思想。

    1 引用 • 2 回帖 • 141 关注
  • 安全

    安全永远都不是一个小问题。

    191 引用 • 813 回帖 • 1 关注
  • 友情链接

    确认过眼神后的灵魂连接,站在链在!

    24 引用 • 373 回帖 • 1 关注
  • SOHO

    为成为自由职业者在家办公而努力吧!

    7 引用 • 55 回帖 • 65 关注
  • SVN

    SVN 是 Subversion 的简称,是一个开放源代码的版本控制系统,相较于 RCS、CVS,它采用了分支管理系统,它的设计目标就是取代 CVS。

    29 引用 • 98 回帖 • 688 关注
  • RabbitMQ

    RabbitMQ 是一个开源的 AMQP 实现,服务器端用 Erlang 语言编写,支持多种语言客户端,如:Python、Ruby、.NET、Java、C、PHP、ActionScript 等。用于在分布式系统中存储转发消息,在易用性、扩展性、高可用性等方面表现不俗。

    49 引用 • 60 回帖 • 396 关注
  • OnlyOffice
    4 引用 • 12 关注
  • HHKB

    HHKB 是富士通的 Happy Hacking 系列电容键盘。电容键盘即无接点静电电容式键盘(Capacitive Keyboard)。

    5 引用 • 74 回帖 • 430 关注
  • QQ

    1999 年 2 月腾讯正式推出“腾讯 QQ”,在线用户由 1999 年的 2 人(马化腾和张志东)到现在已经发展到上亿用户了,在线人数超过一亿,是目前使用最广泛的聊天软件之一。

    45 引用 • 557 回帖 • 160 关注
  • RESTful

    一种软件架构设计风格而不是标准,提供了一组设计原则和约束条件,主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

    30 引用 • 114 回帖 • 2 关注
  • JWT

    JWT(JSON Web Token)是一种用于双方之间传递信息的简洁的、安全的表述性声明规范。JWT 作为一个开放的标准(RFC 7519),定义了一种简洁的,自包含的方法用于通信双方之间以 JSON 的形式安全的传递信息。

    20 引用 • 15 回帖 • 19 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖
  • Kubernetes

    Kubernetes 是 Google 开源的一个容器编排引擎,它支持自动化部署、大规模可伸缩、应用容器化管理。

    109 引用 • 54 回帖 • 3 关注
  • 开源

    Open Source, Open Mind, Open Sight, Open Future!

    402 引用 • 3521 回帖 • 1 关注
  • API

    应用程序编程接口(Application Programming Interface)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

    76 引用 • 429 回帖
  • Swagger

    Swagger 是一款非常流行的 API 开发工具,它遵循 OpenAPI Specification(这是一种通用的、和编程语言无关的 API 描述规范)。Swagger 贯穿整个 API 生命周期,如 API 的设计、编写文档、测试和部署。

    26 引用 • 35 回帖
  • 程序员

    程序员是从事程序开发、程序维护的专业人员。

    544 引用 • 3531 回帖
  • Facebook

    Facebook 是一个联系朋友的社交工具。大家可以通过它和朋友、同事、同学以及周围的人保持互动交流,分享无限上传的图片,发布链接和视频,更可以增进对朋友的了解。

    4 引用 • 15 回帖 • 458 关注
  • 百度

    百度(Nasdaq:BIDU)是全球最大的中文搜索引擎、最大的中文网站。2000 年 1 月由李彦宏创立于北京中关村,致力于向人们提供“简单,可依赖”的信息获取方式。“百度”二字源于中国宋朝词人辛弃疾的《青玉案·元夕》词句“众里寻他千百度”,象征着百度对中文信息检索技术的执著追求。

    63 引用 • 785 回帖 • 237 关注
  • 机器学习

    机器学习(Machine Learning)是一门多领域交叉学科,涉及概率论、统计学、逼近论、凸分析、算法复杂度理论等多门学科。专门研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技能,重新组织已有的知识结构使之不断改善自身的性能。

    76 引用 • 37 回帖
  • NGINX

    NGINX 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 NGINX 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本 0.1.0 发布于 2004 年 10 月 4 日。

    311 引用 • 546 回帖
  • Vditor

    Vditor 是一款浏览器端的 Markdown 编辑器,支持所见即所得、即时渲染(类似 Typora)和分屏预览模式。它使用 TypeScript 实现,支持原生 JavaScript、Vue、React 和 Angular。

    328 引用 • 1715 回帖 • 4 关注
  • 生活

    生活是指人类生存过程中的各项活动的总和,范畴较广,一般指为幸福的意义而存在。生活实际上是对人生的一种诠释。生活包括人类在社会中与自己息息相关的日常活动和心理影射。

    230 引用 • 1454 回帖
  • GAE

    Google App Engine(GAE)是 Google 管理的数据中心中用于 WEB 应用程序的开发和托管的平台。2008 年 4 月 发布第一个测试版本。目前支持 Python、Java 和 Go 开发部署。全球已有数十万的开发者在其上开发了众多的应用。

    14 引用 • 42 回帖 • 705 关注
  • Maven

    Maven 是基于项目对象模型(POM)、通过一小段描述信息来管理项目的构建、报告和文档的软件项目管理工具。

    186 引用 • 318 回帖 • 330 关注