Skip to content

Commit f1836c7

Browse files
committed
v1.0.1 - Invoke function calls with correct context
1 parent e6506b9 commit f1836c7

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "sfobj",
3-
"version": "1.0.0",
3+
"version": "1.0.1",
44
"main": "./index.js",
55
"description": "JS proxy for safe property access.",
66
"repository": "https://github.com/devMYC/sfobj.git",
@@ -10,7 +10,7 @@
1010
"node": ">= 6.0"
1111
},
1212
"scripts": {
13-
"build": "rm -fr ./dist && tsc",
13+
"build": "rm -fr ./dist && tsc && cp ./package.json ./dist",
1414
"codecov": "codecov -f ./coverage/coverage-final.json",
1515
"show:coverage": "open ./coverage/lcov-report/index.html",
1616
"test": "jest --runInBand"

src/index.ts

+10-4
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,26 @@ type SafeProxy<T> = {
1515
export function Safe<T>(v: T): SafeProxy<T> {
1616
let curr = v
1717
const proxy: any = new Proxy(NeverFail, {
18-
apply() {
18+
apply(_, __, args) {
19+
typeof curr === 'function' && (curr = curr(...args))
1920
return proxy
2021
},
2122
get(_, prop) {
23+
let val: any
2224
switch (true) {
2325
case prop === unwrap:
24-
const val = curr
26+
val = curr
2527
curr = v
2628
return val
2729
case prop === Symbol.toPrimitive: return () => Safe.name
2830
case curr == null: break
2931
default:
30-
curr = (curr as any)[prop]
31-
typeof curr === 'function' && (curr = curr())
32+
val = (curr as any)[prop]
33+
if (typeof val === 'function') {
34+
curr = val.bind(curr)
35+
} else {
36+
curr = val
37+
}
3238
break
3339
}
3440
return proxy

tests/index.spec.ts

+9
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,20 @@ test(Safe.name, () => {
44
const obj = {
55
a: 100,
66
b: {
7+
x: 200,
78
c: [
89
{ d: 1e3 },
910
{ e: () => 1e4 },
1011
],
12+
add(y) {
13+
return this.x + y
14+
},
1115
},
1216
f: null,
1317
g: undefined,
18+
add(x: number) {
19+
return this.a + x
20+
},
1421
}
1522

1623
const safeObj = Safe(obj)
@@ -21,5 +28,7 @@ test(Safe.name, () => {
2128
expect((safeObj.g as SafeWrapper<undefined>)[unwrap]).toBe(undefined)
2229
expect(safeObj.b.c[0].d[unwrap]).toBe(1e3)
2330
expect(safeObj.b.c[1].e()[unwrap]).toBe(1e4)
31+
expect(safeObj.add(1)[unwrap]).toBe(101)
32+
expect(safeObj.b.add(2)[unwrap]).toBe(202)
2433
expect((safeObj.b.c[100] as any).xx().yy.zz().or[1].whatever['key'][unwrap]).toBe(undefined)
2534
})

0 commit comments

Comments
 (0)