Skip to content

Instantly share code, notes, and snippets.

@sofish
Created June 11, 2015 05:43

Revisions

  1. sofish revised this gist Jun 11, 2015. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions invert.js
    Original file line number Diff line number Diff line change
    @@ -5,8 +5,8 @@ function invert(tree) {
    var inverted = tree.reverse();

    for(var cur in inverted) {
    if(!inverted.hasOwnProperty(cur)) continue;
    ret.push(inverted[cur] instanceof Array ? invert(inverted[cur]) : inverted[cur]);
    if(!inverted.hasOwnProperty(cur)) continue;
    ret.push(inverted[cur] instanceof Array ? invert(inverted[cur]) : inverted[cur]);
    }

    return ret;
  2. sofish created this gist Jun 11, 2015.
    18 changes: 18 additions & 0 deletions invert.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    function invert(tree) {
    if (!tree instanceof Array || tree.length === 1) return tree;

    var ret = [];
    var inverted = tree.reverse();

    for(var cur in inverted) {
    if(!inverted.hasOwnProperty(cur)) continue;
    ret.push(inverted[cur] instanceof Array ? invert(inverted[cur]) : inverted[cur]);
    }

    return ret;
    }

    var tree = [[['a'], 'b', ['c', 'd', null]], 'f', [['g'], 'h', ['i']]];

    console.log(invert(tree));
    // [ [ [ 'i' ], 'h', [ 'g' ] ], 'f', [ [ null, 'd', 'c' ], 'b', [ 'a' ] ] ]
    14 changes: 14 additions & 0 deletions invert_es5.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    'use strict';

    function invert(tree) {
    if (!tree instanceof Array || tree.length === 1) return tree;

    return tree.reverse().map(function (cur) {
    return Array.isArray(cur) ? invert(cur) : cur;
    });
    }

    var tree = [[['a'], 'b', ['c', 'd', null]], 'f', [['g'], 'h', ['i']]];

    console.log(invert(tree));
    // [ [ [ 'i' ], 'h', [ 'g' ] ], 'f', [ [ null, 'd', 'c' ], 'b', [ 'a' ] ] ]