你可能已经读过10个CoffeeScript一行代码技巧,惊艳你的朋友,这篇文章受到一篇关于Scala一行代码的帖子的启发,该帖子发表在HN上。我想用LiveScript及其推荐的基础库prelude.ls来展示一些一行代码,惊艳我的朋友。你可以在LiveScript网站上自己尝试所有这些代码。
无括号链式调用很不错。
$ \.content .find \.date-author .children \a .text!split ' ' .0 #=> 'George'
func!
是一个带感叹号的调用,等价于func()
。在非歧义的情况下,你不需要使用点来访问内容。你可以使用前导反斜杠创建没有空格的字符串字面量。你也可以使用.0
代替[0]
。
部分应用的运算符也很不错。
map (* 2), [1 to 5] #=> [2, 4, 6, 8, 10]
你可以将运算符作为函数在LiveScript中使用,方法是将它们括在括号中。你还可以部分应用它们,如上所示。
几乎就像SQL一样!
# some data table1 = * id: 1 name: \george * id: 2 name: \mike * id: 3 name: \donald table2 = * id: 2 age: 21 * id: 1 age: 20 * id: 3 age: 26 result = [{id, name, age} for {id, name} in table1 for {id:id2, age} in table2 when id is id2] #=> [{id: 1, name: "george", age:20}, {id: 2, name: "mike", age: 21},{id:3, name: "donald", age: 26}]
你可以使用星号列出内容。例如,在列出隐式对象时,这很有用。这里还展示了对象解构。
如果有多个嵌套函数调用,使用管道操作符是一种使代码更易读的好方法。
[1 2 3] |> map (* 2) |> filter (> 3) |> fold1 (+) #=> 10
在LiveScript中,如果前面的项目不可调用,则在列出内容时可以省略逗号,就像我们对输入列表所做的那样。
首先,使用内置函数
sum [1 to 5] #=> 15
这太简单了。如果我们没有sum
怎么办?
fold1 (+), [1 to 5] #=> 15
<[ ... ]>
表示一个包含单个单词字符串的列表。
wordList = <[ LiveScript JavaScript prelude.ls ]> tweet = 'This is an example tweet talking about LiveScript and stuff.' any (in words tweet), wordList #=> true
在这里,我们使用了运算符in
,并将其部分应用的第二个参数作为函数。
如果将某个内容乘以一个字符串字面量,它将充当连接符。例如,list * ','
等价于list.join ','
。本示例中还使用了列表推导式和字符串插值。
["Happy Birthday #{if x is 2 then 'dear George' else 'to you'}" for x to 3] * ', ' #=> 'Happy Birthday to you, Happy Birthday to you, Happy Birthday dear George, Happy Birthday to you'
partition
类似于filter
和reject
的组合。
scores = [49 58 76 43 88 77 90] [passed, failed] = partition (> 60), scores passed #=> [76, 88, 77, 90] failed #=> [49, 58, 43]
此处对返回的值进行解构。
有一个内置函数
minimum [14 35 -7 46 98] #=> -7
如果我们没有minimum
怎么办?我们可以使用最小值运算符进行折叠。
fold1 (<?), [14 35 -7 46 98] #=> -7
确定一个数是否为素数。|
是when
的别名
f = -> [p.push x for x from 2 to it | not any (-> x % it is 0), (p ?= [])] and it in p f 12 #=> false f 13 #=> true
有关LiveScript和prelude.ls的更多信息,请关注@gkzahariev。
评论由Disqus提供