| 1 |
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ |
| 2 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 3 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 4 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 5 |
|
| 6 |
//----------------------------------------------------------------------------- |
| 7 |
var BUGNUMBER = 363040; |
| 8 |
var summary = 'Array.prototype.reduce application in array flattening'; |
| 9 |
var actual = ''; |
| 10 |
var expect = ''; |
| 11 |
|
| 12 |
|
| 13 |
//----------------------------------------------------------------------------- |
| 14 |
test(); |
| 15 |
//----------------------------------------------------------------------------- |
| 16 |
|
| 17 |
function test() |
| 18 |
{ |
| 19 |
printBugNumber(BUGNUMBER); |
| 20 |
printStatus (summary); |
| 21 |
|
| 22 |
function flatten(arr) |
| 23 |
{ |
| 24 |
function op(partial, item) |
| 25 |
{ |
| 26 |
if (item instanceof Array) |
| 27 |
Array.prototype.push.apply(partial, flatten(item)); |
| 28 |
else |
| 29 |
partial.push(item); |
| 30 |
|
| 31 |
return partial; |
| 32 |
} |
| 33 |
|
| 34 |
return arr.reduce(op, []); |
| 35 |
} |
| 36 |
|
| 37 |
expect = [1, 2, 3]; |
| 38 |
actual = flatten([1, 2, 3]); // [1, 2, 3] |
| 39 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 40 |
|
| 41 |
expect = [1, 2, 3]; |
| 42 |
actual = flatten([1, [2], 3]); // [1, 2, 3] |
| 43 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 44 |
|
| 45 |
expect = [2, 3]; |
| 46 |
actual = flatten([[], 2, 3]); // [2, 3] |
| 47 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 48 |
|
| 49 |
expect = [1, 2, 3]; |
| 50 |
actual = flatten([[1], 2, 3]); // [1, 2, 3] |
| 51 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 52 |
|
| 53 |
expect = [4]; |
| 54 |
actual = flatten([[[[4]]]]); // [4] |
| 55 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 56 |
|
| 57 |
expect = [1, 2, 3]; |
| 58 |
actual = flatten([1, [2, [3]]]); // [1, 2, 3] |
| 59 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 60 |
|
| 61 |
expect = []; |
| 62 |
actual = flatten([[[[[]]]]]); // [] |
| 63 |
reportCompare(expect + '', actual + '', summary + ': ' + expect); |
| 64 |
} |