记一次面试题

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

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

/**

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');

    }

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

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

    324 引用 • 1395 回帖

相关帖子

13 回帖

欢迎来到这里!

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

注册 关于
请输入回帖内容 ...
  • visus

    客气了,帅哥哥

    1 回复
  • 其他回帖
  • visus

    这个世界很多都人,性格不一样的,别把自己努力这么轻易给别人的不答复而否定了,我反正没看出问题,是不是没防空或者大数据批量处理没考虑,我是菜鸡的 JS

    1 回复
  • huangkangyi1

    不是这些小问题,建议了解下 es6,很多地方几行代码就能搞定

    function getUnUsedKeys(allKeys, usedKeys) {
    
    
    	//TODO
    	let all = new Set(Array.from(new Array(allKeys)).map((v, k) => k))
    	let used = new Set(usedKeys)
    	let difference = new Set([...all].filter(x => !used.has(x)));
    	return Array.from(difference)
    }
    
  • visus

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

  • 查看全部回帖

推荐标签 标签

  • 数据库

    据说 99% 的性能瓶颈都在数据库。

    330 引用 • 614 回帖
  • 小薇

    小薇是一个用 Java 写的 QQ 聊天机器人 Web 服务,可以用于社群互动。

    由于 Smart QQ 从 2019 年 1 月 1 日起停止服务,所以该项目也已经停止维护了!

    34 引用 • 467 回帖 • 693 关注
  • HTML

    HTML5 是 HTML 下一个的主要修订版本,现在仍处于发展阶段。广义论及 HTML5 时,实际指的是包括 HTML、CSS 和 JavaScript 在内的一套技术组合。

    103 引用 • 294 回帖
  • 大数据

    大数据(big data)是指无法在一定时间范围内用常规软件工具进行捕捉、管理和处理的数据集合,是需要新处理模式才能具有更强的决策力、洞察发现力和流程优化能力的海量、高增长率和多样化的信息资产。

    89 引用 • 113 回帖
  • Tomcat

    Tomcat 最早是由 Sun Microsystems 开发的一个 Servlet 容器,在 1999 年被捐献给 ASF(Apache Software Foundation),隶属于 Jakarta 项目,现在已经独立为一个顶级项目。Tomcat 主要实现了 JavaEE 中的 Servlet、JSP 规范,同时也提供 HTTP 服务,是市场上非常流行的 Java Web 容器。

    162 引用 • 529 回帖 • 3 关注
  • NetBeans

    NetBeans 是一个始于 1997 年的 Xelfi 计划,本身是捷克布拉格查理大学的数学及物理学院的学生计划。此计划延伸而成立了一家公司进而发展这个商用版本的 NetBeans IDE,直到 1999 年 Sun 买下此公司。Sun 于次年(2000 年)六月将 NetBeans IDE 开源,直到现在 NetBeans 的社群依然持续增长。

    78 引用 • 102 回帖 • 643 关注
  • Log4j

    Log4j 是 Apache 开源的一款使用广泛的 Java 日志组件。

    20 引用 • 18 回帖 • 41 关注
  • 工具

    子曰:“工欲善其事,必先利其器。”

    275 引用 • 682 回帖
  • Q&A

    提问之前请先看《提问的智慧》,好的问题比好的答案更有价值。

    6554 引用 • 29428 回帖 • 246 关注
  • OnlyOffice
    4 引用 • 23 关注
  • Markdown

    Markdown 是一种轻量级标记语言,用户可使用纯文本编辑器来排版文档,最终通过 Markdown 引擎将文档转换为所需格式(比如 HTML、PDF 等)。

    163 引用 • 1450 回帖
  • AngularJS

    AngularJS 诞生于 2009 年,由 Misko Hevery 等人创建,后为 Google 所收购。是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入等。2.0 版本后已经改名为 Angular。

    12 引用 • 50 回帖 • 423 关注
  • 创业

    你比 99% 的人都优秀么?

    82 引用 • 1398 回帖 • 1 关注
  • RESTful

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

    30 引用 • 114 回帖 • 1 关注
  • 星云链

    星云链是一个开源公链,业内简单的将其称为区块链上的谷歌。其实它不仅仅是区块链搜索引擎,一个公链的所有功能,它基本都有,比如你可以用它来开发部署你的去中心化的 APP,你可以在上面编写智能合约,发送交易等等。3 分钟快速接入星云链 (NAS) 测试网

    3 引用 • 16 回帖
  • 阿里云

    阿里云是阿里巴巴集团旗下公司,是全球领先的云计算及人工智能科技公司。提供云服务器、云数据库、云安全等云计算服务,以及大数据、人工智能服务、精准定制基于场景的行业解决方案。

    89 引用 • 345 回帖
  • TensorFlow

    TensorFlow 是一个采用数据流图(data flow graphs),用于数值计算的开源软件库。节点(Nodes)在图中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数组,即张量(tensor)。

    20 引用 • 19 回帖
  • 运维

    互联网运维工作,以服务为中心,以稳定、安全、高效为三个基本点,确保公司的互联网业务能够 7×24 小时为用户提供高质量的服务。

    148 引用 • 257 回帖
  • JRebel

    JRebel 是一款 Java 虚拟机插件,它使得 Java 程序员能在不进行重部署的情况下,即时看到代码的改变对一个应用程序带来的影响。

    26 引用 • 78 回帖 • 623 关注
  • Hibernate

    Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,使得 Java 程序员可以随心所欲的使用对象编程思维来操纵数据库。

    39 引用 • 103 回帖 • 685 关注
  • 招聘

    哪里都缺人,哪里都不缺人。

    189 引用 • 1056 回帖
  • 面试

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

    324 引用 • 1395 回帖
  • 游戏

    沉迷游戏伤身,强撸灰飞烟灭。

    169 引用 • 799 回帖
  • Unity

    Unity 是由 Unity Technologies 开发的一个让开发者可以轻松创建诸如 2D、3D 多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

    25 引用 • 7 回帖 • 245 关注
  • 导航

    各种网址链接、内容导航。

    37 引用 • 168 回帖 • 1 关注
  • Google

    Google(Google Inc.,NASDAQ:GOOG)是一家美国上市公司(公有股份公司),于 1998 年 9 月 7 日以私有股份公司的形式创立,设计并管理一个互联网搜索引擎。Google 公司的总部称作“Googleplex”,它位于加利福尼亚山景城。Google 目前被公认为是全球规模最大的搜索引擎,它提供了简单易用的免费服务。不作恶(Don't be evil)是谷歌公司的一项非正式的公司口号。

    49 引用 • 192 回帖
  • 微信

    腾讯公司 2011 年 1 月 21 日推出的一款手机通讯软件。用户可以通过摇一摇、搜索号码、扫描二维码等添加好友和关注公众平台,同时可以将自己看到的精彩内容分享到微信朋友圈。

    129 引用 • 793 回帖