Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

utils.js compact 함수 #5

Open
ledgku opened this issue Oct 21, 2019 · 1 comment
Open

utils.js compact 함수 #5

ledgku opened this issue Oct 21, 2019 · 1 comment
Assignees
Labels
question Further information is requested

Comments

@ledgku
Copy link
Member

ledgku commented Oct 21, 2019

utils.js compact 함수의 동작이 이해하기 어렵다.

  • compactQueue: 배열 내에 undefined를 제거하는 함수
var compactQueue = function compactQueue(queue) {
    while (queue.length > 1) {
        var item = queue.pop();
        var obj = item.obj[item.prop];

        if (isArray(obj)) {
            var compacted = [];

            for (var j = 0; j < obj.length; ++j) {
                if (typeof obj[j] !== 'undefined') {
                    compacted.push(obj[j]);
                }
            }

            item.obj[item.prop] = compacted;
        }
    }
};
  • compact: ?
var compact = function compact(value) {
    var queue = [{ obj: { o: value }, prop: 'o' }];
    var refs = [];

    for (var i = 0; i < queue.length; ++i) {
        var item = queue[i];
        var obj = item.obj[item.prop];

        var keys = Object.keys(obj);
        for (var j = 0; j < keys.length; ++j) {
            var key = keys[j];
            var val = obj[key];
            if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
                queue.push({ obj: obj, prop: key });
                refs.push(val);
            }
        }
    }

    compactQueue(queue);

    return value;
};
@ledgku ledgku added the question Further information is requested label Oct 21, 2019
@ledgku ledgku self-assigned this Oct 21, 2019
@ledgku
Copy link
Member Author

ledgku commented Oct 21, 2019

테스트

>> const qs = require("qs");

>> console.log(qs.utils.compact({"a": { "b": { "c" : 1, "d": 2 }, "e": 3 }, "k": 4}));
{ a: { b: { c: 1, d: 2 }, e: 3 }, k: 4 }

>> console.log(qs.utils.compact({a: 1, b: 2, c: [1,2,3, undefined]}));
{ a: 1, b: 2, c: [ 1, 2, 3 ] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant