게으른개발너D

[Falsy type] Compact Object ⭐️ 본문

알고리즘/과제

[Falsy type] Compact Object ⭐️

lazyhysong 2023. 7. 5. 15:57

https://leetcode.com/problems/compact-object/description/

 

Compact Object - LeetCode

Can you solve this real interview question? Compact Object - Given an object or array obj, return a compact object. A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the objec

leetcode.com

Given an object or array obj, return a compact object. A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false.

You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.

 

Example 1:

Input: obj = [null, 0, false, 1]
Output: [1]
Explanation: All falsy values have been removed from the array.

Example 2:

Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: obj["a"] and obj["b"][0] had falsy values and were removed.

Example 3:

Input: obj = [null, 0, 5, [0], [false, 16]]
Output: [5, [], [16]]
Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.

 

Constraints:

  • obj is a valid JSON object
  • 2 <= JSON.stringify(obj).length <= 106

 

solution

/**
 * @param {Object} obj
 * @return {Object}
 */
var compactObject = function(obj) {
  let answer;
  if(Array.isArray(obj)) {
    answer = [];
    for(let i = 0; i < obj.length; i++) {
      const value = obj[i];
      if(value !== null && value !== 0 && value !== false && value !== "") {
        let secondVal = value;
        if(typeof value === 'object') {
          secondVal = compactObject(obj[i]);
        } 
        answer.push(secondVal);
      }
    }
  } else {
    answer = {};
    for(const key in obj) {
      const value = obj[key];
      if(value !== null && value !== 0 && value !== false && value !== "") {
        let secondVal = value;
        if(typeof value === 'object') {
          secondVal = compactObject(obj[key]);
        } 
        answer[key] = secondVal;
      }
    }
  }

  return answer;
};

 

 

solution 2

reduce와 falsy type의 특징을 이용한 풀이

/**
 * @param {Object} obj
 * @return {Object}
 */
var compactObject = function (obj) {
    //check is it an array
    if (Array.isArray(obj)) {
        return obj.reduce((acc, cur) => {
            let value = compactObject(cur);

            if (value) {
                acc.push(value);
            }
            
            return acc;
        }, [])
    }
    //check is it an object
    if (typeof obj === 'object' && obj !== null) {
        return Object.keys(obj).reduce((acc, key) => {
            let value = compactObject(obj[key]);

            if (value) {
                acc[key] = value;
            }
            
            return acc
        }, {});
    }

    // If it is neither an array, nor an object, nor null, return the value (which can be a string, number, or boolean)
    return obj || null;
};

 

 

solution 3

var compactObject = function(obj) {
  if (obj === null) return null;
  if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject);
  if (typeof obj !== "object") return obj;

  const compacted = {};
  for (const key in obj) {
    let value = compactObject(obj[key]);
    if (Boolean(value)) compacted[key] = value;
  }

  return compacted;
};

 


1. typeof

1. typeof가 반환할 수 있는 값

Undefined "undefined"
Null "object" 
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol(ECMAScript 2015에서 추가) "symbol"
호스트 객체 (JS 환경에서 제공) 구현체마다 다름
Function 객체 (ECMA-262 표현으로는 [[Call]]을 구현하는 객체) "function"
다른 모든 객체 "object"

 

2. 예시

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!

typeof 42n === 'bigint';


// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof always returns a string
typeof String("abc") === 'string'; // but never use this form!


// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!


// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';


// Objects
typeof {a:1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';


// The following is confusing. Don't use!
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String("abc") === 'object';


// Functions
typeof function(){} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';


// Null
// This stands since the beginning of JavaScript
typeof null === 'object';

 

 

 

2. falsy values

거짓 같은 값(Falsy, falsey로 쓰이기도 함) 은 Boolean에서 false로 평가되는 값이다.

1. falsy로 쓰이는 값들

0 숫자 zero
-0 음수 zero
0n BigInt 불리언으로 사용될 경우, 숫자와 같은 규칙을 따름. 0n은 거짓 같은 값.
"" string
null null - 아무런 값도 없음
undefined undefined - 원시값
NaN NaN - 숫자가 아님

 

2. 예시

falsy 값은 Boolean 문맥에서 false로 변환되므로, 아래의 모든 if 블록은 실행되지 않는다.

if (false)
if (null)
if (undefined)
if (0)
if (-0)
if (0n)
if (NaN)
if ("")

 

Comments