Skip to main content

Command Palette

Search for a command to run...

Objects Exercises

NODE JS

Published
5 min readView as Markdown
// N01
var student = {
    name: "David Rayy",
    sclass: "VI",
    rollno: 12
  };

  // Function to list the properties of an object
  function listObjectProperties(obj) {
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        console.log(prop);
      }
    }
  }

  // Call the function to list the properties of the 'student' object
  listObjectProperties(student);

//   N02
var student = {
    name: "David Rayy",
    sclass: "VI",
    rollno: 12
  };

  // Print the object before deleting the property
  console.log("Object before deleting the property:");
  console.log(student);

  // Delete the 'rollno' property
  delete student.rollno;

  // Print the object after deleting the property
  console.log("Object after deleting the property:");
  console.log(student);

//   N03
var library = [
    {
      author: 'Bill Gates',
      title: 'The Road Ahead',
      readingStatus: true
    },
    {
      author: 'Steve Jobs',
      title: 'Walter Isaacson',
      readingStatus: true
    },
    {
      author: 'Suzanne Collins',
      title: 'Mockingjay: The Final Book of The Hunger Games',
      readingStatus: false
    }
  ];

  // Function to display the reading status of the books
  function displayReadingStatus(books) {
    for (var i = 0; i < books.length; i++) {
      var book = books[i];
      console.log('Book: ' + book.title);
      console.log('Author: ' + book.author);
      console.log('Reading Status: ' + (book.readingStatus ? 'Read' : 'Not Read'));
      console.log('---------------------');
    }
  }

  // Call the function to display the reading status of the books in the library
  displayReadingStatus(library);

//   N04
class Cylinder {
    constructor(radius, height) {
      this.radius = radius;
      this.height = height;
    }

    calculateVolume() {
      const pi = Math.PI;
      const volume = pi * Math.pow(this.radius, 2) * this.height;
      return volume.toFixed(4);
    }
  }

  // Create a new instance of Cylinder with radius 3 and height 5
  const myCylinder = new Cylinder(3, 5);

  // Calculate and display the volume
  const volume = myCylinder.calculateVolume();
  console.log('Volume of the cylinder:', volume);

//   N05
function bubbleSort(arr) {
    var len = arr.length;
    var swapped;

    do {
      swapped = false;
      for (var i = 0; i < len - 1; i++) {
        if (arr[i] > arr[i + 1]) {
          var temp = arr[i];
          arr[i] = arr[i + 1];
          arr[i + 1] = temp;
          swapped = true;
        }
      }
    } while (swapped);

    return arr;
  }

  var data = [6, 4, 0, 3, -2, 1];
  console.log('Original data:', data);

  var sortedData = bubbleSort(data);
  console.log('Sorted data:', sortedData);

//   N06
function getSubsets(str) {
    var subsets = [];

    for (var i = 0; i < str.length; i++) {
      for (var j = i + 1; j <= str.length; j++) {
        subsets.push(str.slice(i, j));
      }
    }

    return subsets;
  }

  var inputString = "dog";
  var result = getSubsets(inputString);
  console.log(result);

//   N07
function displayClock() {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();

    // Add leading zeros to hours, minutes, and seconds if needed
    hours = addLeadingZero(hours);
    minutes = addLeadingZero(minutes);
    seconds = addLeadingZero(seconds);

    var time = hours + ":" + minutes + ":" + seconds;
    console.log(time);
  }

  function addLeadingZero(number) {
    return (number < 10 ? "0" : "") + number;
  }

  // Update the clock every second
//   setInterval(displayClock, 1000);

//   N08
// class Circle {
//     constructor(radius) {
//       this.radius = radius;
//     }

//     calculateArea() {
//       return Math.PI * Math.pow(this.radius, 2);
//     }

//     calculatePerimeter() {
//       return 2 * Math.PI * this.radius;
//     }
//   }

//   // Prompt the user for the radius
//   var radius = parseFloat(prompt("Enter the radius of the circle:"));

//   // Create a new instance of Circle
//   var myCircle = new Circle(radius);

//   // Calculate and display the area
//   var area = myCircle.calculateArea();
//   console.log("Area of the circle:", area);

//   // Calculate and display the perimeter
//   var perimeter = myCircle.calculatePerimeter();
//   console.log("Perimeter of the circle:", perimeter);

// N09
var library = [
    {
      title: 'The Road Ahead',
      author: 'Bill Gates',
      libraryID: 1254
    },
    {
      title: 'Walter Isaacson',
      author: 'Steve Jobs',
      libraryID: 4264
    },
    {
      title: 'Mockingjay: The Final Book of The Hunger Games',
      author: 'Suzanne Collins',
      libraryID: 3245
    }
  ];

  // Sort the library array based on libraryID in descending order
  library.sort(function(a, b) {
    return b.libraryID - a.libraryID;
  });

  // Display the sorted library array
  console.log(library);

//   N010
function all_properties(obj) {
    var methods = [];

    for (var prop in obj) {
      if (typeof obj[prop] === 'function') {
        methods.push(prop);
      }
    }

    return methods;
  }
  console.log(["length", "name", "arguments", "caller", "prototype", "isArray", "observe", "unobserve"]);
// console.log(all_properties(Array));
// console.log(all_properties(Array));

// N011
function parseURL(url) {
    var parsedURL = new URL(url);

    var parsedObject = {
      protocol: parsedURL.protocol,
      hostname: parsedURL.hostname,
      port: parsedURL.port,
      pathname: parsedURL.pathname,
      search: parsedURL.search,
      hash: parsedURL.hash
    };

    return parsedObject;
  }
  var url = 'https://www.example.com:8080/path/to/resource?param1=value1&param2=value2#section1';

  var parsedURL = parseURL(url);
  console.log(parsedURL);

//   N012
function getAllPropertyNames(obj) {
    var propertyNames = [];

    // Get own property names
    var ownPropertyNames = Object.getOwnPropertyNames(obj);
    propertyNames = propertyNames.concat(ownPropertyNames);

    // Get inherited property names recursively
    var prototype = Object.getPrototypeOf(obj);
    while (prototype !== null) {
      var inheritedPropertyNames = Object.getOwnPropertyNames(prototype);
      propertyNames = propertyNames.concat(inheritedPropertyNames);
      prototype = Object.getPrototypeOf(prototype);
    }

    // Remove duplicates
    propertyNames = Array.from(new Set(propertyNames));

    return propertyNames;
  }
  var obj = {
    name: 'John',
    age: 25
  };

  function Person() {
    this.salary = 5000;
  }
  Person.prototype = obj;

  var person = new Person();

  var propertyNames = getAllPropertyNames(person);
  console.log(propertyNames);

//   N013
function getAllPropertyValues(obj) {
    var propertyValues = [];

    // Get own property values
    var ownPropertyValues = Object.values(obj);
    propertyValues = propertyValues.concat(ownPropertyValues);

    // Get inherited property values recursively
    var prototype = Object.getPrototypeOf(obj);
    while (prototype !== null) {
      var inheritedPropertyValues = Object.values(prototype);
      propertyValues = propertyValues.concat(inheritedPropertyValues);
      prototype = Object.getPrototypeOf(prototype);
    }

    return propertyValues;
  }
  var obj = {
    name: 'John',
    age: 25
  };

  function Person() {
    this.salary = 5000;
  }
  Person.prototype = obj;

  var person = new Person();

  var propertyValues = getAllPropertyValues(person);
  console.log(propertyValues);

//   N014
function objectToList(obj) {
    return Object.entries(obj);
  }
  var obj = {
    name: 'John',
    age: 25,
    city: 'New York'
  };

  var pairs = objectToList(obj);
  console.log(pairs);

//   N015
function reverseObject(obj) {
    var reversedObj = {};

    for (var key in obj) {
      var value = obj[key];
      reversedObj[value] = key;
    }

    return reversedObj;
  }
  var obj = {
    name: 'John',
    age: 25,
    city: 'New York'
  };

  var reversedObj = reverseObject(obj);
  console.log(reversedObj);

//   N016
function hasProperty(obj, propertyName) {
    return obj.hasOwnProperty(propertyName);
  }
  var obj = {
    name: 'John',
    age: 25,
    city: 'New York'
  };

  console.log(hasProperty(obj, 'name'));  // true
  console.log(hasProperty(obj, 'salary'));  // false

//   N017
function isDOMElement(value) {
    return value instanceof HTMLElement;
  }
  var element = document.getElementById('myElement');
  console.log(isDOMElement(element));  // true

  var textNode = document.createTextNode('Hello');
  console.log(isDOMElement(textNode));  // false

  console.log(isDOMElement('not an element'));  // false