Last active
August 29, 2015 14:05
-
-
Save xujihui1985/f2d475674b9342860e90 to your computer and use it in GitHub Desktop.
array flatten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function flatten(arr) { | |
var result=[], | |
concat = Array.prototype.concat, | |
push = Array.prototype.push, | |
element, | |
array = arr.slice(); //shadow copy the array | |
for(var i = 0, l = array.length; i < l; i++) { | |
element = arr[i]; | |
if(isArray(element)) { | |
//for proformance reason, if all element flattened already, do not recurcivly call | |
if(isAllElementFlatten(element)) { | |
result = concat.call(result,element); | |
} | |
else { | |
push.apply(result,flatten(element)); | |
} | |
} | |
else { | |
result.push(element); | |
} | |
} | |
return result; | |
/** helper methods */ | |
function isAllElementFlatten(arr) { | |
return isAll(arr, function(ele) { | |
return !(isArray(ele)); | |
}); | |
} | |
function isAll(arr, predict) { | |
return arr.map(function(ele){ | |
return predict(ele) ? 1 : 0; | |
}).reduce(function(pre, curr){ | |
return pre + curr | |
},0) === arr.length | |
} | |
function isArray(arr) { | |
if(Array.isArray) return Array.isArray(arr); | |
return Object.prototype.toString.call(arr) === '[object Array]'; | |
} | |
} | |
//poorman's unittest | |
function test(){ | |
var testcases = { | |
'test1' : [1,3,[2,3,[3,4]],2,3,[1,2,3]], | |
'test2' : ['a',['b',['c']]], | |
'test3' : [1,[2,[3,[4,[5]]]]] | |
}, | |
baselines = { | |
'test1' : [1,3,2,3,3,4,2,3,1,2,3], | |
'test2' : ['a','b','c'], | |
'test3' : [1,2,3,4,5] | |
}, | |
baseline, | |
actual; | |
for(var testcase in testcases) { | |
baseline = baselines[testcase]; | |
actual = flatten(testcases[testcase]); | |
if(baseline.toString() === actual.toString()) { | |
console.log('Testcase: '+testcase+' passed'); | |
} | |
else { | |
console.log('Testcase: '+testcase+' failed'); | |
} | |
} | |
} | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment