Оcenka-BEL.com - безплатни онлайн тестове, пробни изпити, видео уроци и помощ при писане на задания от литературно и хуманитарно естество

Practical CoffeeScript

Публикувано: 2017-09-11 17:05:43

Свързано изображение

Practical CoffeeScript

Introduction

CoffeeScript is a tiny language which compiles into JavaScript. It literally makes you code less and write more. It makes your code highly understandable when you come back to it at some point in the future, saves time and enhances the clarity of the code which leads to less bugs in your code.

The article will have two parts: in the first we are going to go through the basics of CoffeeScript and in the second part we are going to create a Tic Tac Toe game using CoffeeScript.

Installation

Install it globally using the node’s package manager (npm) by typing: npm install coffee-script -g in your shell. You should install it globally so you can later access it in Command Prompt/Terminal using coffee … 
CoffeeScript files have the .coffee file extension 
Later you go in the directory where your project is and either manually compile your .coffee script or set a watcher that will compile your script each time it is saved with different contents.

To manually compile: 
Go to the directory where the script is: cd E:\apps\something\logic 
Compile it: coffee -c app.coffee 
This will create an app.js in the same directory.

You most likely want app.js to be refreshed each time you save the file, therefore you compile it and add a watcher by typing: 
coffee -cw app.coffee

CoffeeScript Basics

In CoffeeScript you do not have to declare variables, although often you would need to set an initial value. We do not have to type semi-colons ( ; ).

Therefore you do the following: 
hasBody = true instead of var hasBody = true;

You can skip parenthesis but that is desirable only for outermost function calls.

Therefore, you can do the following: 
$("messages") .show 'slow' instead of $("messages").show('slow');

Indentation matters a lot in CoffeeScript. You should indent with two spaces or a tab

Example:

if hasBody
  alert "Hello Body"
else
  alert "No Body"

In CoffeeScript all on, yes and true refer to the Boolean true. 
* off, no and false* refer to the Boolean false.

You can use is and isnt to check for equality or lack of equality ( === and !==
You can use then to make single-line conditionals 
You can use and and or to refer to && and || 
You can compare a value with two other values without repeating yourself 
Example of these concepts:

x = 53
y = 40
z = 33
b = true
if b is on and x is 53 and z < y > 11 then alert "ALRIGHT"

You can use filters using the when keyword which is really useful 
You can loop over arrays using for value in arrayName

Example of filters and array loops:


spartacus = {
  type: 'cat'
  legs: 4,
  eyes: 2,
  fur: true
  name: "Spartacus"
}
shrimpy = {
    legs : 4,
    type : 'dog',
    name : "Achilles"
  }

pets = [spartacus,shrimpy]

myPet = pet for pet in pets when pet.name is "Spartacus"

console.log myPet

This logs the spartacus object
Notice that you can specify the statement to be executed in the loop before you write the loop. This is useful when writing one-liner loops. 
Alternatively, you could refactor it like that:

for pet in pets when pet.name is "Spartacus"
  myPet = pet
  alert myPet.name
  console.log myPet

You can create inclusive and exclusive ranges.

someValues = [0..10]
sameValues = [0...11]

When converted to JavaScript the arrays look like that:

someValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

sameValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

You can loop over objects using for key,value of objectName 
You can nest variables and js inside strings using #{variableName}.

Example of looping over objects, filters and string interpolation:

for key,value of spartacus when key is "type"
  console.log "KEY : #{key}, VALUE: #{value}"

Logs KEY : type, VALUE: cat to the console

To create functions you use -> followed by the definition. If you have to add parameters you add them inside parenthesis () before the ->

You can add default values by setting the parameter to equal something.

Examples of functions with CoffeeScript:

myCoffee = ->
  console.log "C'est un cafe"

makeCoffee = (brand = "Hogwarts") ->
  console.log "Making a coffee #{brand}-style"

myCoffee()
makeCoffee()

Logs to the console:

C’est un cafe 
Making a coffee Hogwarts-style

You can use @ instead of this

Example:

$("a").click ->
  $(@).hide 'slow'

This becomes

  $("a").click(function() {
    return $(this).hide('slow');
  });

CoffeeScript facilitates OOP and inheritance as well. You can define classes

class Animal
  constructor: (@name, @breed) ->
    @.introduce = ->
      console.log "Hi, I am #{@.name}, one hell of a #{@.breed}"

husky = new Animal("Johny", "Siberian Husky")
husky.introduce()

Outputs in console:

Hi, I am Johny, one hell of a Siberian Husky

typing @ before the parameter’s name in the constructor would cause the parameter to be immediately set in the constructor. Alternatively, you could just write @.name = name in the constructor function.

You can extend classes as well:

class Dog extends Animal

Dog.prototype.bark = ->
      console.log "#{@name} barks!"

newHusky = new Dog("Lassy", "Some Husky")
newHusky.introduce()
newHusky.bark()

This code outputs:

Hi, I am Lassy, one hell of a Some Husky 
Lassy barks!

Your functions could receive an unlimited number of arguments if you add  (ellipsis) after the parameter. In this case, all values after and including that parameter would be added to it in the form of an array.

Here is how you could achieve that:

showAwards = (awards...) ->
  console.log ("Awards collected : #{awards.join ","}")

showAwards "Award 1", "Award 2", "Award 3"

The code above outputs:

Awards collected : Award 1,Award 2,Award 3

The last thing I want to mention here is that when you are inside any function CoffeeScript automatically returns the result from the last statement in it. Therefore, all your functions have a return value. Just as you saw in the anonymous function that handles anchor clicks above.