Skip to content
/ by Public

make delegated properties in JavaScript Class like by of kotlin

Notifications You must be signed in to change notification settings

hikaMaeng/by

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

by

make delegated properties in JavaScript Class like by of kotlin

step1. make delegator with by.getValue, by.setValue

class TestDelegate{
  [by.getValue](target, k){return target.map.get(k) ?? `no ${k}`;}
  [by.setValue](target, k, v){target.map.set(k, v);}
}

step2. declare delegated properties using static

class Test{

  //declare delegated properties with class name
  static name = TestDelegate;
  static company = TestDelegate;
  static other = TestDelegate;
  
  map = new Map;
}

step3. by.set

by.set(Test);

step4. use properties

const test = new Test;
test.name = "hika";
test.company = "bsidesoft";
 
console.log(test.name); //hika
console.log(test.company); //bsidesoft
console.log(test.other); //no other

related posting(korean) [js] 코틀린 delegated Property 흉내내기

advanced usage

using delegate instance

class TestDelegate{
  [by.getValue](target, k){return target.map.get(k) ?? `no ${k}`;}
  [by.setValue](target, k, v){target.map.set(k, v);}
}

class Test{
  static company = new TestDelegate; //<-----instance!
  map = new Map;
}
by.set(Test);

using standard delegate

lazy

class Test{

static sum = lazy(({data})=>data.reduce((acc,v)=>acc + v));

  data;

  constructor(...arg){
    this.data = [...arg];
  }
}
by.set(Test);
const test = new Test(1, 2, 3, 4, 5);
console.log(test.sum); //15
console.log(test.sum); //15

when get first, call initializer and memoization. just like https://kotlinlang.org/docs/reference/delegated-properties.html#lazy

observe

class Test{
  static name = observe('', (target, k, oldV, newV)=>console.log(oldV, 'to', newV));
}
by.set(Test);

const test = new Test;
test.name = 'hika'; // '' to 'hika'
test.name = 'maeng'; // 'hika' to 'maeng'

when called setter, nofity changes to observer function just like https://kotlinlang.org/docs/reference/delegated-properties.html#observable

About

make delegated properties in JavaScript Class like by of kotlin

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published