-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApiChain.js
75 lines (69 loc) · 2.13 KB
/
ApiChain.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const Prototype2ApiChain = new Map();
const OBJ_prototype = Object.getPrototypeOf( {} );
export const
setProp = ( refObj, k, ApiChainLocal )=>
{
if( typeof refObj[ k ] == 'function' )
{ ApiChainLocal.prototype[ k ] = function( ...args )
{ if( k.startsWith('get') )
{
if( this.length )
return this[ 0 ][ k ]( ...args )
else
return;
}
this.forEach( el => el[ k ]( ...args ) );
return this;
}
}else
{ Object.defineProperty( ApiChainLocal.prototype, k,
{ get : function(){ if( this.length ) return this[ 0 ][ k ] }
, set: function( v )
{ this.forEach( el => el[ k ] = v );
return v
}
} );
}
}
function
applyPrototype( elementProto, refObj )
{ let ChainClass = Prototype2ApiChain.get(elementProto);
if( ChainClass )
return ChainClass;
class ApiChainLocal extends Array{}
const applied = {"constructor":1};
for ( let obj=refObj; obj !== OBJ_prototype && obj != null ; obj = Object.getPrototypeOf(obj))
{
for( let k of Object.getOwnPropertyNames(obj) )
if( !applied[k])
{ setProp( refObj, k, ApiChainLocal );
applied[k]=1;
}
}
Prototype2ApiChain.set(elementProto, ApiChainLocal);
return ApiChainLocal;
}
export function
ApiChain( elOrArr, elementProto = undefined )
{
const isArr = Array.isArray( elOrArr );
const arr = isArr ? elOrArr : [ elOrArr ];
if( ! elementProto )
elementProto = Object.getPrototypeOf( isArr ? elOrArr[0] : elOrArr );
const refObj = arr[0];
if( elementProto === OBJ_prototype )
{
class ApiChainLocal extends Array{}
for( let k in refObj )
setProp( refObj, k, ApiChainLocal );
const ret = new ApiChainLocal();
ret.push(...arr);
return ret;
}
// class object
const ApiChain = applyPrototype( elementProto, refObj );
const ret = new ApiChain();
ret.push(...arr);
return ret;
}
export default ApiChain;