custom stringify

by harsh dand

JavaScript

function customStringify(obj) {
    if (obj === null) return 'null';
    if (typeof obj === 'undefined') return 'undefined';
    if (typeof obj === 'string') return `"${obj}"`;
    if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj);
    if (typeof obj === 'function') return undefined;    
    
    if (Array.isArray(obj)) {
        const elements = obj
            .map(element => customStringify(element))
            .filter(element => element !== undefined);
        if (elements.length === 0) return '[]';
        return `[${elements.join(`,`)}]`;
    }
    
    if (typeof obj === 'object') {
        const properties = Object.keys(obj)
            .map(key => {
                const value = customStringify(obj[key]);
                if (value === undefined) return undefined;
                return `"${key}":${value}`;
            })
            .filter(prop => prop !== undefined);
        if (properties.length === 0) return '{}';
        return `{${properties.join(`,`)}}`;
    }
}

// Example usage
const testObject = {
    name: "John Doe",
    age: 30,
    isStudent: false,
    grades: [95, 87, 92],
    address: {
        street: "123 Main St",
        city: "Anytown"
    },
    sayHello: function() { console.log("Hello!"); }
};

console.log(customStringify(testObject));
console.log(JSON.stringify(testObject)); // Compare with built-in JSON.stringify