es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

Suggest to enhance `cloneDeep` with custom clone rules

Open jacksonyu opened this issue 1 year ago • 1 comments

Hello, do you guys think it is a good idea to make cloneDeep to support custom colne rules ?

try this

import {cloneDeep} from 'es-toolkit';
import Decimal from 'decimal.js';

const a = cloneDeep({decimalVal: new Decimal(1)})
console.log(Decimal.isDecimal(a.decimalVal));

a.decimalVal is no longer a Decimal and will lost all functions.

so, if we can enhance cloneDeep to receive custom rules like this:

export function cloneDeep<T>(obj: T, options?:{
  customRules?:{
    check: (value: any) => boolean
    clone: (value: any) => any
  }[]
}): T {
  return cloneDeepImpl(obj, options);
}

then, we can solve the problem:

const a = cloneDeep({decimalVal: new Decimal(1)},{
  customRules:[{
    check:val=>Decimal.isDecimal(val),
    clone:val=> new Decimal(val)
  }]
})

Looking forward to your comments.

by the way , the isEqual function would be more powerful if it support custom rules too.

jacksonyu avatar Aug 10 '24 02:08 jacksonyu