tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

sort-utils.js (1115B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 "use strict";
      6 
      7 /**
      8 * Sorts object by keys in alphabetical order
      9 * If object has nested children, it sorts the child-elements also by keys
     10 *
     11 * @param {object} which should be sorted by keys in alphabetical order
     12 */
     13 function sortObjectKeys(object) {
     14  if (object == null) {
     15    return null;
     16  }
     17 
     18  if (Array.isArray(object)) {
     19    for (let i = 0; i < object.length; i++) {
     20      if (typeof object[i] === "object") {
     21        object[i] = sortObjectKeys(object[i]);
     22      }
     23    }
     24    return object;
     25  }
     26 
     27  return Object.keys(object)
     28    .sort(function (left, right) {
     29      return left.toLowerCase().localeCompare(right.toLowerCase());
     30    })
     31    .reduce((acc, key) => {
     32      if (typeof object[key] === "object") {
     33        acc[key] = sortObjectKeys(object[key]);
     34      } else {
     35        acc[key] = object[key];
     36      }
     37      return acc;
     38    }, Object.create(null));
     39 }
     40 
     41 module.exports = {
     42  sortObjectKeys,
     43 };