toss / es-toolkit

A modern JavaScript utility library that's 2-3 times faster and up to 97% smaller—a major upgrade to lodash.
https://es-toolkit.slash.page
Other
6.29k stars 269 forks source link

Suggest to enhance `cloneDeep` with custom clone rules #367

Open jacksonyu opened 1 month ago

jacksonyu commented 1 month ago

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.

raon0211 commented 1 month ago

I guess this is a functionality that we should support. I am not sure about how we support this. Let me think for a while which interface would be best.