标签: coffeescript

CoffeeScript:初始化或增加数组中的值

我的应用程序具有关于一组固定国家/地区的不同类型的数据,这些数据保持在一致顺序的数组中.

data = 
  oranges: [1,2,3]
  apples: [1,2,3]
  cabbages: [1,2,3]
Run Code Online (Sandbox Code Playgroud)

这些数组通过各种标准组合成新数组,我发现自己想要编写这样的代码:

fruit = []
for key, arr of data                  # For each array
  if key in ['oranges', 'apples']     # It it meets certain criteria
    for val, i in arr                 # Use the values in the creation of a new array
      fruit[i] += val
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为如果fruit[i]未初始化+=将不起作用.

有很多方法可以解决这个问题.

1)fruit首先用零填充新数组:

for i in [0..len]
  fruit[i] = 0
Run Code Online (Sandbox Code Playgroud)

2)检查是否fruit[i]存在:

if fruit[i]?
  fruit[i] += val 
else 
  fruit[i] = val …
Run Code Online (Sandbox Code Playgroud)

javascript coffeescript

2
推荐指数
1
解决办法
3555
查看次数

带D3的简单多线图

http://jsfiddle.net/ytvka/4/

我知道之前已经问过这个问题,但是我无法用这些例子来弄清楚我做错了什么.

我想创建一个简单的6点,3系列图表,其数据看起来像:

data = [
  {"key":"D78","date":"2013-09-23T17:26:21.258Z","value":1.25}, 
  {"key":"D78","date":"2013-09-23T17:28:21.258Z","value":2.25},
  {"key":"R71","date":"2013-09-23T17:26:21.258Z","value":2.45},
  {"key":"R71","date":"2013-09-23T17:28:21.258Z","value":2.85},
  {"key":"X44","date":"2013-09-23T17:26:21.258Z","value":3.87},
  {"key":"X44","date":"2013-09-23T17:28:21.258Z","value":3.87}
] 
Run Code Online (Sandbox Code Playgroud)

没有什么令人兴奋的.我理想的做法是从这些数据中制作一个3系列折线图.

svg = d3.select(selector).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom).append("g")

x = d3.time.scale().range([ 0, width ])
y = d3.scale.linear().range([ height, 0 ])
format = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ")

valueLine = d3.svg.line().interpolate("basis")
  .x((d) ->
    console.log format.parse(d.date)
    x(format.parse(d.date))
  )
  .y((d) ->
    console.log d.value
    y d.value
  )

  svg.append("path").attr("class", "line")
    .attr "d", valueLine(u.where(data, key: "X44"))
Run Code Online (Sandbox Code Playgroud)

哪个生成SVG: <path class="line" d="M137998238125800,-287L137998250125800,-287"></path>

这段代码只是使用lodash拉出了一个系列.问题是:屏幕上没有任何内容.它贯穿并抓住了价值,但没有线条.我发现现有的例子既复杂又没有很好地解释(http://bl.ocks.org/mbostock/3884955)或缺少关键部分(http://www.d3noob.org/2013/01/adding-超过一行到图 - in.html).

  1. 我的代码出了什么问题?
  2. 如何添加其他系列(R71,D78)? …

coffeescript d3.js

2
推荐指数
1
解决办法
1万
查看次数

如何使用Coffeescript和shellJS编写可执行的shell脚本?

我已经使用NPM安装了coffeescript和shellJS.我有一个测试脚本shtest.coffee:

#!/usr/local/bin/coffee
require 'shelljs/global'
echo 'hello'
exit 1
Run Code Online (Sandbox Code Playgroud)

用咖啡运行脚本工作正常:

$ coffee shtest.coffee
hello
Run Code Online (Sandbox Code Playgroud)

或者用shjs:

$ shjs shtest.coffee
hello
Run Code Online (Sandbox Code Playgroud)

但不是直接:

$ chmod u+x shtest.coffee
$ ./shtest.coffee
./shtest.coffee: line 2: require: command not found
hello
Run Code Online (Sandbox Code Playgroud)

改变shebang指向/usr/local/bin/js没有帮助.

看起来该脚本是作为bash脚本运行的.我究竟做错了什么?OS X Snow Leopard.

javascript bash shell shebang coffeescript

2
推荐指数
1
解决办法
949
查看次数

从`coffee`可执行文件调用函数

请原谅noob问题,但为什么我不能(几乎)从coffeeREPL中调用(几乎)任何标准函数(或者从TextMate中编写并运行的文件)?

变量赋值工作,函数没有.

例子:

coffee> string = "string"
'string'
coffee> list = [1,2,3]
[ 1, 2, 3 ]
coffee> num = 42
42
coffee> opposite = true
true
coffee> num = -42 if opposite
-42
Run Code Online (Sandbox Code Playgroud)

但

coffee> alert "Hello, World"
ReferenceError: alert is not defined
    at repl:1:5
    at REPLServer.replDefaults.eval (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:33:28)
    at repl.js:239:12
    at Interface.<anonymous> (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/repl.js:62:9)
    at Interface.EventEmitter.emit (events.js:117:20)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:117:20)
Run Code Online (Sandbox Code Playgroud)

和

coffee> print "Hello"
ReferenceError: print …
Run Code Online (Sandbox Code Playgroud)

textmate node.js coffeescript read-eval-print-loop

2
推荐指数
1
解决办法
1499
查看次数

是否有使用IF/ELSE语句的替代方法

题

更多是出于好奇,但我想知道如何将if语句重构为更清晰/更不易碎的东西.从我读过的,多态可能有用吗?

在示例中,我只想返回第一辆车,如果color:'red'是真的话.

CoffeeScript的

example: () ->
    cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}]
    if cars[0].color is 'red' 
    then cars[0]
    else cars[1]
Run Code Online (Sandbox Code Playgroud)

使用Javascript

  example: function() {
    var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
    if (cars[0].color === 'red') {
      return cars[0];
    } else {
      return cars[1];
    }
  }
Run Code Online (Sandbox Code Playgroud)

我理解这个问题可能由于模糊性而被关闭或移动

javascript coffeescript

2
推荐指数
2
解决办法
1万
查看次数

如何在Ember.js中保存具有'date'类型属性的模型?

我正在尝试在Ember.js中保存包含日期属性的对象.

在商店上调用createRecord()之后,新对象在页面上显示,但是在调用save()时,日期属性从页面中消失.模型上的所有其他属性类型都不会显示此出现然后消失的行为.这是一些示例代码:

App = Ember.Application.create()

App.IndexRoute = Ember.Route.extend
    model: () -> @store.find "post"

App.Post = DS.Model.extend
    time: DS.attr "date"
    body: DS.attr "string"

App.IndexController = Ember.ArrayController.extend
    actions:
        createPost: () ->
            body = @get 'newBody'
            post = @store.createRecord 'post',
                body: body
                time: Date.now()
            @set 'newBody', ''
            post.save()

App.Post.FIXTURES = [
    id: 1
    time: new Date("2013-9-30")
    body: "fixture post"
]
Run Code Online (Sandbox Code Playgroud)

请看这个jsfiddle进行演示.

javascript coffeescript ember.js ember-data

2
推荐指数
1
解决办法
3066
查看次数

Coffeescript类共享属性

我在coffeescript中发现了一个非常奇怪的行为.

class Foo
    list: []
    add: (val)->
        @list.push(val)


x = new Foo()
x.add(1)
console.log(x.list.length) // 1

y = new Foo()
y.add(1)
console.log(y.list.length) // 2
Run Code Online (Sandbox Code Playgroud)

所以当你看到@list属性以一种奇怪的方式在两个类实例之间共享时.在coffeescript中,我以前从未遇到类似的问题.

coffeescript

2
推荐指数
1
解决办法
56
查看次数

写入coffeescript中的文本文件

我目前正在向控制台写一串文本以获取测试原因,如下所示:

console.log JSON.stringify @classification

如何将其写入coffeescript中的文本文件?

干杯

詹姆士

在node.js中 - 我想写入我选择的文件名 - 而不是默认的日志文件.

coffeescript

2
推荐指数
1
解决办法
3193
查看次数

AngularJS + Coffeescript - 'Hello World'指令不起作用

我不能让最简单的指令在我的AngularJS + Coffeescript项目中起作用.

我在directives.coffee中有这个代码:

'use strict'
app_name = "myApp"
app = angular.module "#{app_name}.directives", []

# Directive to include the version number of my project
app.directive 'appVersion', [
'version', (version) ->
    (scope, element, attrs) ->
    element.text version
]

# Hello world directive
app.directive 'hello', () ->
    restict: 'E'
    template: '<div>Hello World</div>'
Run Code Online (Sandbox Code Playgroud)

在我的模板中,当我这样做时

<span app-version></span>
<hello></hello>
Run Code Online (Sandbox Code Playgroud)

然后显示版本号(0.1),表明第一个指令正常工作,但标签不会被任何东西取代.

知道我做错了什么吗?

我也试过这个,但也没用:

# Hello world directive
app.directive 'hello', ->
    class Habit
        constructor: ->
            restict: 'E'
            template: '<div>Hello World</div>'
Run Code Online (Sandbox Code Playgroud)

javascript coffeescript angularjs angularjs-directive

2
推荐指数
1
解决办法
2017
查看次数

mongodb在try catch中遇到异常崩溃的节点

try
    p = req.params.name
    Item.update('name': p, req.body , {upsert: true}, (err) ->
      if err?
        throw err
      res.send("ok")
      )
  catch e
    handle_error(e, "Error salvando hoja de vida.", res)
Run Code Online (Sandbox Code Playgroud)

这在我的代码中产生了一个错误 - 这没关系,但是为什么我的nodejs程序崩溃,即使我在这里试试了?

错误是:

MongoError: Mod on _id not allowed
Run Code Online (Sandbox Code Playgroud)

(所以它必须在更新调用中)我特意寻找一种捕获错误的方法,我已经知道如何摆脱它.

mongodb node.js coffeescript

2
推荐指数
1
解决办法
4956
查看次数