/**
* 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;
};
Author Archives: Larry Battle
Code of the day: Javascript Flatten()
Posted by Larry Battle
on May 7, 2013
No comments
Google Go: recover() example
Posted by Larry Battle
on May 6, 2013
No comments
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?");
}
Demo: http://play.golang.org/p/xu9Jd1YI0T More information here:
Output:
Error: You shall not pass!
No problems occurred
panic: Where am I going?
goroutine 1 [running]:
main.main()
Effective Go - The Program Language
Code of the Day: Coffeescript + jQuery, enforce max length for all input elements
Posted by Larry Battle
on March 10, 2013
1 comment
Enforce max length in all browsers since some browsers, IE8, don’t support maxlength for all input elements.
Coffeescript
# requires jQuery 1.6+
enforceMaxLength = ->
$("[maxlength]").on "blur", ->
$(@).val (index,val) ->
val.substring 0, $(@).attr("maxlength")
enforceMaxLength()
Javascript
// Generated by CoffeeScript 1.6.1 (function() { var enforceMaxLength; enforceMaxLength = function() { return $("[maxlength]").on("blur", function() { return $(this).val(function(index, val) { return val.substring(0, $(this).attr("maxlength")); }); }); }; enforceMaxLength(); }).call(this); |
Video of the day: 3d printing overview by OffBook PBS
Posted by Larry Battle
on March 5, 2013
No comments
Will 3D Printing Change the World?

Recent Comments