??? javascript is mutable !!!

There goes another few hours.. :-(
Please dont spread this around and dont say I wrote this after ~20 years of programming.
But JS is kinda mutable ????

var o1,o2
function fChange(arg){
    arg.k += '-new'
    return arg

o1 = {k: 'v1'}
o2 = {k: 'v2'}
o2 = fChange(o1)
console.log('1A) o1=' + JSON.stringify(o1))
console.log('1B) o2=' + JSON.stringify(o2))
function fChange2(arg){
    arg = $.extend(true,{},arg)
    arg.k += '-new'
    return arg
o1 = {k: 'v1'}
o2 = {k: 'v2'}
o2 = fChange2(o1)
console.log('2A) o1=' + JSON.stringify(o1))
console.log('2B) o2=' + JSON.stringify(o2))

Results in:

1A) o1={"k":"v1-new"}
1B) o2={"k":"v1-new"}
2A) o1={"k":"v1"}
2B) o2={"k":"v1-new"}

Result 1A) is utterly amazing !
And terrifying !
Is the object o1 passed in by reference ? Yes it appears so.

Can be seen in fChange2(). Use jquery $.extend() to make a (deep or not) value copy.

arg = $.extend(true,{},arg)

And o1 remains unmutated, as we’d want it to be. See result 2A)
Alternative, not needing jquery, is:

arg = JSON.parse(JSON.stringify(arg))

Using the JSON lib also has the advantage that you dont have to handle cases where arg is Array containing objects in which case you’d need to use arg = $.extend(true,[],arg)

Please be silent and enjoy your knowledge !

atomize = KIS = SOC = smart !

Was writing a CList class and was gently reminded of some principles of programming.

  • atomize = KIS = SOC = smart !
  • atomize : for procs the less the better.
  • KIS : keep-it-simple.
  • SOC : seperation-of-concern : this proc is for this, that one for that.
  • smart! : a wise thing to do ; that will pay off ; rather sooner ; and surely later.

Atomize = KIS = Seperation of concern = smart !
@IMPORTANT ! Strictly maintain:
- 1) Callformat: {keyword:xx, data:xx}
//eg: {"keyword":"ReqSetListFilter","data":{"filters":[{"dbfd":"groupNr","xval":"20"}]}}
//eg: {"keyword":"ReqGetListRecNr","data":{"recNr":1}}
Do not use:
//eg: {"keyword":"ReqSetListFilter","filters":[{"dbfd":"groupNr","xval":"10"}]}
//eg: {"keyword":"ReqGetListRecNr","recNr":0}
- 2) Do not return anything if not specifically a fGetXX call. eg: do not return recs on fEdit etc. Only return true, or false if something went wrong.
Except maybe some feedback info eg on fDoBulkUpdate(data.data) return ~nTouched. No, not even then. Use fGetListCount > fDoBulkUpdate > fGetListCount

In the end you’ll end up with a nice CList class that, as by accident, quite easily handles filters (arrOriIdxs =[]) (flyweight pattern ?) and bulk updates.

Gotto run…