Skip to content

Iterations + Contribution #4

@ghost

Description

Since the object/array .length doesn't change, why is the need to calculate the .length on each iteration cycle ? I've also improved the code, following the D.R.Y and readability philosopy.

Old code:

module.exports = function sortObject (obj, comparator) {
    // Arrays
    if ( Array.isArray(obj) ) {
        const result = []
        for ( let i = 0; i < obj.length; ++i ) {
            // Fetch
            let value = obj[i]

            // Recurse if object or array
            if ( value != null && typeof value === 'object' ) {
                value = sortObject(value, comparator)
            }

            // Push
            result.push(value)
        }
        return result
    }

    // Objects
    else {
        const result = {}
        const sortedKeys = Object.keys(obj).sort(comparator)
        for ( let i = 0; i < sortedKeys.length; ++i ) {
            // Fetch
            const key = sortedKeys[i]
            let value = obj[key]

            // Recurse if object or array
            if ( value != null && typeof value === 'object' ) {
                value = sortObject(value, comparator)
            }

            // Push
            result[key] = value
        }
        return result
    }
}

New one:

var iterArray = function(arr, obj, toKeyVal, comparator) {
    var result = toKeyVal ? {} : [],
        value = null;

    arr.forEach(function(elem) {
        value = toKeyVal ? obj[elem] : elem;
        if (value !== null && typeof value === 'object') {
            value = sortObject(value, comparator);
        }
        if (toKeyVal) {
            result[elem] = value;
        } else {
            result.push(value);
        }
    });
    return toKeyVal ? result : result.sort();
};

var sortObject = function (obj, comparator) {
    // Arrays
    if ( Array.isArray(obj) ) {
        return iterArray(obj, obj, false, comparator);
    }

    // Objects
    else {
        return iterArray(Object.keys(obj).sort(),
                obj, true, comparator);
    }
};

15 hours later: replaced return result; to return toKeyVal ? result : result.sort();, so the array elements to be sorterd alphabetically in case of

d: ['b','d','e','a','c']

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions