震惊小伙伴的单行代码●CoffeeScript篇

栏目: CoffeeScript · 发布时间: 8年前

内容简介:震惊小伙伴的单行代码●CoffeeScript篇

几年前,函数式编程的复兴正值巅峰,一篇介绍 Scala 中 10 个单行函数式代码 的博文在网上走红。很快地,一系列使用其他语言实现这些单行代码的文章也随之出现,比如 Haskell , Ruby , Groovy , Clojure , Python , C# , F# , CoffeeScript

每篇文章都令人印象深刻的揭示了这些语言中一些出色优秀的编程特征。编程高手们利用这些技巧提高编程速度、改进软件质量,编程初学者能从这些简洁的预防中学到各种编程语言的真谛。本《震惊小伙伴的单行代码系列》将逐一介绍这些各种编程语言单行代码文章,供大家学习参考。

1. 让列表中的每个元素都乘以2

[1..10].map (i) -> i*2

i * 2 for i in [1..10]

2. 求列表中的所有元素之和

[1..1000].reduce (t, s) -> t + s

(reduce == reduceLeft, reduceRight 也可以)

3. 判断一个字符串中是否存在某些词

wordList = ["coffeescript", "eko", "play framework", "and stuff", "falsy"]
tweet = "This is an example tweet talking about javascript and stuff."

wordList.some (word) -> ~tweet.indexOf word

下面的例子会返回匹配的单词:

wordList.filter (word) -> ~tweet.indexOf word

~ is not a special operator in CoffeeScript, just a dirty trick. It is the bitwise NOT operator, which inverts the bits of it’s operand. In practice it equates to -x-1. Here it works on the basis that we want to check for an index greater than -1, and -(-1)-1 == 0 evaluates to false.

4. 读取文件

fs.readFile 'data.txt', (err, data) -> fileText = data

同步版本:

fileText = fs.readFileSync('data.txt').toString()

In node.js land this is only acceptable for application start-up routines. You should use the async version in your code.

5. 祝你生日快乐!

[1..4].map (i) -> console.log "Happy Birthday " + (if i is 3 then "dear Robert" else "to You")

下面这一版读起来更像是伪代码:

console.log "Happy Birthday #{if i is 3 then "dear Robert" else "to You"}" for i in [1..4]

6. 过滤列表中的数值

(if score > 60 then (passed or passed = []) else (failed or failed = [])).push score for score in [49, 58, 76, 82, 88, 90]

更函数式的方法:

[passed, failed] = [49, 58, 76, 82, 88, 90].reduce ((p,c,i) -> p[+(c < 60)].push c; p), [[],[]]

7. 获取XML web service数据并分析

这里用json代替XML:

request.get { uri:'path/to/api.json', json: true }, (err, r, body) -> results = body

8. 找到列表中最小或最大的一个数字

Math.max.apply @, [14, 35, -7, 46, 98] # 98
Math.min.apply @, [14, 35, -7, 46, 98] # -7

9. 并行处理

Not there yet. You can create child processes on your own and communicate with them, or use the WebWorkers API implementation. Skipping over.

10. “Sieve of Eratosthenes”算法

下面的代码可以写成一行吗?

sieve = (num) ->
    numbers = [2..num]
    while ((pos = numbers[0]) * pos) <= num
        delete numbers[i] for n, i in numbers by pos
        numbers.shift()
    numbers.indexOf(num) > -1

跟紧凑的版本:

primes = []
primes.push i for i in [2..100] when not (j for j in primes when i % j == 0).length

真正的一行实现:

(n) -> (p.push i for i in [2..n] when not (j for j in (p or p=[]) when i%j == 0)[0]) and n in p
(n) -> (p.push i for i in [2..n] when !(p or p=[]).some((j) -> i%j is 0)) and n in p

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

阿里巴巴正传:我们与马云的“一步之遥”

阿里巴巴正传:我们与马云的“一步之遥”

方兴东、刘伟 / 江苏凤凰文艺出版社 / 2015-1 / 45.00

十几年来,方兴东与马云每年一次,老友聚首,开怀畅谈,阿里上市前,作者再次与马云深度对话,阿里上市前的布局,深入探讨了一系列人们关心的话题。 本书忠实记录了阿里壮大、马云封圣的历史。作者通过细致梳理和盘点,对阿里巴巴的15年成长史进行了忠实回顾。从海博翻译社到淘宝网,从淘宝商城到天猫,从支付宝到阿里云计算,从拉来软银的第一笔投资到纽交所上市,作者对其中涉及到的人物、细节都有生动展现;对于马云、......一起来看看 《阿里巴巴正传:我们与马云的“一步之遥”》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具