js interview coding question

infinite currying

multiply(2)(3) ---> 6 --> finite

function multiply (a){
    return function(b){
        a*b
    }
}

multiply(2)(3)(2)(3)() -->36--> infinite

function multiply(a){
    return function(b){
        if(b) return multiply(a*b)
        else return a
    }
}
// recersivelly calling fun multiply if b is present

deep clone object

const obj={
 a : 1,
 b : 2,
 C : {
     d : 3,
  }
}

const obj2 = obj
obj2.b = 3
console.log(obj2,obj)
// obj2 and obj points to same location in memory(reference) , 
// so when obj2.b = 3 is changed it also effected obj
const obj={
 a : 1,
 b : 2,
 C : {
     d : 3,
  }
}

const obj2 = JSON.parse(JSON.stringify(obj))
obj2.b = 3
console.log(obj2,obj)
// when obj2.b = 3 is changed it not effected obj
const obj={
 a : 1,
 b : 2,
 C : {
     d : 3,
  }
e : Date.now(),
f : undefined,
}

const obj2 = JSON.parse(JSON.stringify(obj))
obj2.b = 3
console.log(obj2,obj)
// but it cant hold date(half is removed and converted into string),
// undefined is removed
function createDeepClone(obj){
  let cloneData = Array.isArray(obj) ? [] : {}
  for(let key in obj){
      let value = obj[key]
      if(typeof value !=='object'){
           cloneData[key] = value 
       }else if(typeof value =='object'){
           cloneData[key] = createDeepClone(value)
       }else if(value instanceof Date){
           cloneData[key] = new Date(value.getTime())
       }
    }
    return cloneData
}

const obj2 = createDeepClone(obj)
// obj2.b = 3
console.log(obj2,obj)

method chaining

calculate.sum(10,5,2).add(4).multiply(6).subtract(3).value()

const calculate={
    val : 0,
    total : 0,
    add(no){
        this.val = this.val + no
        return this
     },
    multiply(no){
        this.val = this.val * no
        return this
     },
    subtract(no){
        this.val = this.val - no
        return this
     },
    sum(...args){
        this.total = args.reduce((acc,val)=>acc+val,0)
        this.val = this.val + this.total
        return this
    },
    value(){
        return this.val
    }
}

const result = calculate.sum(10,5,2).add(4).multiply(6).subtract(3).value()
console.log(result)
class Calculate {
  constructor() {
    this.val = 0;
    this.total = 0;
  }
  add(no) {
    this.val = this.val + no;
    return this;
  }
  multiply(no) {
    this.val = this.val * no;
    return this;
  }
  subtract(no) {
    this.val = this.val - no;
    return this;
  }
  sum(...args) {
    this.total = args.reduce((acc, val) => acc + val, 0);
    this.val = this.val + this.total;
    return this;
  }
  value() {
    return this.val;
  }
}

const calculate = new Calculate();
const result = calculate.sum(10, 5, 2).add(4).multiply(6).subtract(3).value();
console.log(result);