Monthly Archives: May 2013

Code of the day: Javascript Flatten()

/**
* Returns an array that contains non-array elements.
* If an element is an array, then the element is replaced by the content of the array.
* @param{Array} 
* @return{Array} return null if no arguments are passed.
* @example 
    flatten([[1,2],3,[4]]); // returns [1,2,3,4];
*/
var flatten = function(arr){
	if(!Array.isArray(arr)){
		return (arr === null || arr === undefined) ? null : [arr];
	}
	var result = [], obj;
	for(var i = 0, len = arr.length; i < len; i++){
		obj = arr[i];
		if(Array.isArray(arr)){
			obj = flatten(obj);
		}
		result = result.concat( obj );
	}
    return result;
};

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
Twitter

Google Go: recover() example

Here’s an example of how to use recover() in Google Go.

package main

import "fmt"

func gandalf( doTalkTo bool ){
	defer catch()
	if(doTalkTo){
		// Panic stops execution of the current function and stops unwinding the stack, calling an deferred functions along the way.
		panic("You shall not pass!")	
	}
}
// catch() must be called as a deferred 
func catch(){
	// recover() regains control over the program execution when panic() is called.
	// recover() returns is the argument passed from panic()
	if r := recover(); r != nil {
		fmt.Println("Error:", r)
	} else {
		fmt.Println("No problems occurred")
	}
}
func main() {
	gandalf(true)
	gandalf(false)
	//unwinds to the top of the stack and ends the program
	panic("Where am I going?");
}


Output:
Error: You shall not pass!
No problems occurred
panic: Where am I going?

goroutine 1 [running]:
main.main()

Demo: http://play.golang.org/p/xu9Jd1YI0T

More information here:
Effective Go - The Program Language

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
Twitter