惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园_首页
雷峰网
雷峰网
V
Visual Studio Blog
爱范儿
爱范儿
A
About on SuperTechFans
量子位
N
Netflix TechBlog - Medium
Microsoft Security Blog
Microsoft Security Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
S
SegmentFault 最新的问题
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 沙加

前端设计模式之 MPVC Part 3 前端设计模式之 MPVC Part 2 前端设计模式之 MPVC Part 1 App Engine 缓存与数据一致性 常用跨浏览器效果 同步请求真的有那么恐怖? Google Closure 的单元测试纪要 双飞翼布局的选区问题 HTML 5 之旅 part 1 - 无头苍蝇 bind, delegate, live 三者的区别 Objective-C 学习笔记 - part 12 - 多线程 Objective-C 学习笔记 - part 11 - 错误处理 Objective-C 学习笔记 - part 10 - 选择器 Objective-C 学习笔记 - part 9 - 静态标记的类型 Objective-C 学习笔记 - part 8 - 快速枚举 Objective-C 学习笔记 - part 7 - 相关引用 Objective-C 学习笔记 - part 6 - 类别与扩展 Objective-C 学习笔记 - part 5 - 申明属性 Objective-C 学习笔记 - part 4 - 协议
一个 JS 面试题目
沙加 · 2011-09-26 · via 博客园 - 沙加

看到一个 JS 题:

只允许使用 +-*/ 和 Math.* ,求一个函数 y = f(x, a, b);

当 x > 100 时返回 a 的值,否则返回 b 的值,不能使用 if else 等条件语句,也不能使用  |, ?, 数组

试解如下:

<script>

function transition(x, a, b){

x = Math.max(x, 0); // 先处理负数。

if(x == 100){

   return b;

}

var tmp = Math.ceil(Math.min(Math.max(x - 100, 0), 1));

return a*tmp + b*Math.abs(tmp-1);

}

console.log(transition(101, 1, 0));// 1

console.log(transition(100.5, 1, 0));// 1

console.log(transition(100, 1, 0)); //0

console.log(transition(99.5, 1, 0));// 0

console.log(transition(99, 1, 0));// 0

console.log(transition(-23, 1, 0));// 0

</script>

一般思路是转换为 0, 1 的特殊值问题进行处理。