JavaScript 邀请:10 行令你朋友惊讶的 Javascript 代码

chenge · 2013年05月01日 · 最后由 chenge 回复于 2016年07月04日 · 5032 次阅读

网上似乎没有,哪位有兴趣写一个?参考那个 Ruby 版本。

我 js 较弱,就不献丑了。

我倒.. CoffeeScript 版本原来已经有了... JS 基本上就这样,只是语法难看些 http://ricardo.cc/2011/06/02/10-CoffeeScript-One-Liners-to-Impress-Your-Friends.html

#2 楼 @jiyinyiyong 我是觉得 js 至少还是需要的,这个是很好的学习方式吧。

#3 楼 @chenge JS 调用的 API 都和 coffee 一样,大部分代码都一致的 在想要不要直接用 coffee 编译器翻译下.. 好像意义不大

#4 楼 @jiyinyiyong 要不你开个头,写两条,我也献丑一下。

#5 楼 @chenge 这活是翻译 coffee 到 JS 呀,嗯,试一下,前边简单的交给我了..

列表生成这个真心残疾,只能参考 Gist 定义函数来用了。

p = console.log;

range = function(n, m, exp){
  if (!exp) exp = function(x) {return x};
  return Array.apply(null, {length: m}).map(function(_, i){
    return exp(i) + n;
  });
};

列表中的每项乘 2

p(range(0,10, function(x){return x * 2}));

对列表中的数字求和

p(range(1,1000).reduce(function(x, y){return x + y}, 0))

检查字符串是否包括单词

从 coffee 版本改写

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

p(wordList.some(function(word) {
  return tweet.indexOf(word) >= 0;
}));

读取文件

Node 原生的,参数挺多

fileText = require("fs").readFileSync('data.txt', "utf8");

生日快乐

range(1,4).map(function(i){
  if (i == 3) {
    p("Happy Birthday " + "dear Robert")
  } else {
    p("Happy Birthday to You")
  }
});

过滤数列

p([49, 58, 76, 82, 88, 90].filter(function(x) {return x > 60}));

读取并解析 JSON Web service

用 JS 就只用 JSON 了,Node 环境

require("http").get("http://nodejs.org/api/http.json", function(res){
  json = ""
  res.on("data", function(chunk) {json += chunk;});
  res.on("end", function(){ p(JSON.parse(json)) });
});

在数列中查找最大数或最小数

JS 让手动传递上下文,, 最近觉得好奇怪的..

p(Math.max.apply(this, [14, 35, -7, 46, 98]))
p(Math.min.apply(this, [14, 35, -7, 46, 98]))

并行处理

缺..

埃拉托斯特尼筛法

缺..

#8 楼 @jiyinyiyong range 有没有更好读的写法?

#8 楼 @jiyinyiyong chrome 中测试那个 p 会报错?你是用什么测试的?

原生 JS 没有语法来生成带长度数组,我现在只能用

Array.apply(null, {length: m})

接着跟 map 方法来扩展

Array.apply(null, {length: m}).map(function(_, i){ return i + 1})

剩下我只能会 Google 了 :p http://stackoverflow.com/questions/3895478/does-javascript-have-a-range-equivalent

#10 楼 @chenge Node 呀,不然就不可能读本地文件

#12 楼 @jiyinyiyong 就是那个 apply 比较费解一点,别的都还好。

#13 楼 @chenge 一个 trick, 也很费解..

#12 楼 @jiyinyiyong Array.apply(null, {length: m}), 这个怎么理解。 p(Math.max.apply(null, [14, 35, -7, 46, 98])), 不要 this 是不是好一点?

#16 楼 @jiyinyiyong MDN:Apply, Calls a function with a given this value and arguments provided as an array (or an array like object).

那个参数是 json object, 可以当数组么?

#17 楼 @chenge JS 里可以说没有数组,因为数组都是对象来实现的 默认的一个数组,除了内部细节 (我不怎么清楚) 不同,整个都是对象 比如这样...


array =
  0: 1
  1: 2
  length: 2
  push: (value) ->
    @[@length] = value
    @length += 1
    @

  pop: ->
    pop = @[@length]
    delete @[@length]
    @length -= 1 if @length > 0
    pop

  toString: ->
    string = "["
    self = @
    [0...@length].forEach (number) ->
      # console.log self,number
      string += self[number].toString()
      string += ", "
    string += "]"
    string = string[...-3] + "]" if string[-3..] is ", ]"
    string

console.log array.toString(), array.length
array.push 4
console.log array.toString(), array.length
array.pop()
console.log array.toString(), array.length
array.pop()
console.log array.toString(), array.length
array.pop()
console.log array.toString(), array.length
array.push 4
console.log array.toString(), array.length
array.push 3
console.log array.toString(), array.length
[1, 2] 2
[1, 2, 4] 3
[1, 2] 2
[1] 1
[] 0
[4] 1
[4, 3] 2

Ruby China 用的 Markdown 有 Bug 么,,, @length 变成 @user?

#18 楼 @jiyinyiyong 明白了,参考《good parts》一书。谢谢你的代码,很有启发性。

#1 楼 @fredwu 这个 console 是怎么装的呢?

#18 楼 @jiyinyiyong

埃拉托斯特尼筛法

range = function(start, count, exp){
  if (!exp) exp = function(x) {return x};
  return Array.apply(null, {length: count}).map(function(_, i){
    return exp(i) + start;
  });
};

Array.prototype.last = function(){
    return this.slice(-1)[0];
};

p = console.log;
n = 120;
primes = range(2,n-2);

index = 0;
while(Math.pow(primes[index],2) <= primes.last()){
    prime = primes[index];
    primes = primes.filter(function(ele){ 
                return ele == prime || ele % prime != 0;
        });
    index++;
}
p(primes);


Ruby 版本的在那里?

#20 楼 @fresh_fish

› sudo ln /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc /bin/jsc

#18 楼 @jiyinyiyong 为了处理 @ 后用户名带各种下划线,只能在 markdown 之前全部替换掉了。碰到了恶心的 CoffeeScript @ 和变量名是分开的 syntax class,这样就没法替换回来了。

这个还真不好处理了。如果在 Markdown callback 里处理,用户名已经被替换了,没法知道原来是啥。如果之前处理,需要先自己解析 Markdown 语法一遍,找出哪些是代码。

FYI: https://github.com/ruby-china/ruby-china/blob/master/lib/markdown.rb#L148

@doitian 这么说是 coffee 语法高亮问题.. 貌似把语法保存成 Ruby 看起来也不会走样~

chenge Ruby 学习汇集,请推荐内容 提及了此话题。 07月04日 11:35
需要 登录 后方可回复, 如果你还没有账号请 注册新账号