Reading:
Groovy for JS Developers

Groovy for JS Developers

Metamug
Groovy for JS Developers


Most of the developers who are using javascript can move to groovy as it is powerful and dynamic language. Groovy makes it easier for the javascript developer as it uses fewer lines of code which results in the same output as the javascript code.

There is little difference found in groovy wrt to javascript some of them are as follows i.e function is replaced by def in groovy, {} are replaced by [].

Advantages of Groovy

  • less code.
  • less time.
  • simplified coding.
  • more concise and easier to read.

Code in javascript

data = {country:"IND", score:193, wicket:6, batsmen:[{name:"V. Kohli", score:55, strike:false}, {name:"A. Rahane", score:75, strike:true}]}

function score(data){
    console.log(data.country+" "+data.score+"/"+data.wicket)
    data.batsmen.forEach(function(batsman){
         console.log(batsman.name +" " + batsman.score + (batsman.strike?"*":""))
    })
}

score(data)

Code in groovy

data = [country:"IND", score:193, wicket:6, batsmen:[[name:"V. Kohli", score:55, strike:false], [name:"A. Rahane", score:75, strike:true]]]

def score(data){
    println (data.country+" "+data.score+"/"+data.wicket)
    data.batsmen.each{
        println (it.name +" " + it.score + (it.strike?"*":""))
    }
}

score(data)

Functions in javascript and groovy

Three ways of declaring functions in javascript

//With function name
function add(a,b){ return a+b}
//Without function name
add = (a,b) => { return a+b}
//With variable name
add = function(a,b){ return a+b}
//You can call all three with function the same
add(5,5)

With the above 3 examples, we can pass a function as an argument in javascript, but in groovy passing function as an argument doesn't work. So in groovy, we use closures for passing a function as an argument.

def sigmoid(f,x){ 
return 1/(1+Math.E**-f(x))
}
def f = { x ->
    return 2*x**2+4*x+4
}
println sigmoid(f, args[0] as Double)

Here's an example of an arrow function being passed as an argument.

var op = (a,b) => { return a*b }
def call(a,b, fn){
    console.log(fn(a,b))
}
call(1,2,op)

Closures in groovy

The same concept is used in javascript with closures. The syntax slightly defers as instead of () => {}, all the code is placed in curly braces with arrow inside { -> }

def op = { a,b -> return a*b }
def call(a,b, fn){
    println fn(a,b)
}
call(1,2,op)

Parsing JSON Object

var obj = {}
obj.country = "India"
obj.batsmen = []

var b = {} 
b.name= "V. Kohli"
b.score = 55
b.strike = false

obj.batsmen.push(b)

b = {} 
b.name= "R. Sharma"
b.score = 99
b.strike = true

obj.batsmen.push(b)

console.log(obj)

JSON object in groovy


import groovy.json.JsonOutput

def obj = [:] //define map
obj.batsmen = [] //define array 
def b = [:] 
b.name= "V. Kohli"
b.score = 55
b.strike = false

obj.batsmen.push(b)

b = [:] 
b.name= "R. Sharma"
b.score = 99
b.strike = true

//push second object
obj.batsmen.push(b)

//groovy syntax
println obj
//json syntax
println JsonOutput.toJson(obj)

Groovy Object Notation

The above code will give two outputs. The difference you see is the braces used for defining maps.

[batsmen:[[name:R. Sharma, score:99, strike:true], [name:V. Kohli, score:55, strike:false]]]
{"batsmen":[{"name":"R. Sharma","score":99,"strike":true},{"name":"V. Kohli","score":55,"strike":false}]}

{} are used to define objects in javascript i.e. Javascript Object Notation(JSON).

In Groovy { … } are not used to define object as it is reserved for closures. Instead [:] are used in Groovy.

In the groovy example, we are using JsonOutput because the default format printed by Groovy has square braces instead of curly braces for map, which is not correct JSON.

Get subarray from array

To get selected elements from an array we can use the slice() method. Slice method returns the selected element from the given array. In slice method, the first argument is selected as the first element and whereas the second argument is not selected as the last element instead it ends at it.

var ar = [1, 2, 3, 4, 5];
var ar2 = ar.slice(1, 1 + 3);

console.log(ar2)

To get subarray from an array in groovy select the first and last element of the given array using this [start..end].

def ar = [1, 2, 3, 4, 5];
def ar2 = ar[1..3]

println ar2

For Each loop

In javascript forEach() has better readability and less code compared to for loop which is more complex to read, in the below for each example we can print both the item as well as the index of it.

var ar = [1, 2, 3, 4, 5];
ar.forEach((item,i)=>{
    console.log('ar['+i+'] = ' + item)
})

In groovy to get the all the elements from the array it is used. But if you want elements as well as the the index of the array there is a special function eachWithIndex.

def ar = [1, 2, 3, 4, 5];
ar.each{
    println it
}

//for each with index
ar.eachWithIndex{item,i ->
    println "ar[${i}] = ${item}"
}

Round to fixed decimal positions

In both, JS and groovy there are functions available directly on the numbers.

39.3011291.toFixed(3)
39.3011291.round(3)

Math Functions

Math functions like abs, tan, PI are available under Math in groovy and javascript. The following lines of code will work in both javascript and groovy

Math.abs(19-22)
Math.tan(90)
Math.PI


Icon For Arrow-up
Comments

Post a comment