Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/sdgluck/mewt
Browse files Browse the repository at this point in the history
  • Loading branch information
sdgluck committed Mar 29, 2017
2 parents 8def3e9 + 874c5e4 commit 2529eb4
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
20 changes: 14 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ function mewt(target) {
const multiRet = 'push pop shift unshift'
const mutArrMethods = 'reverse sort splice fill copyWithin'
const nonMutArrMethods = 'filter map concat slice'

const mutationTraps = ['setPrototypeOf', 'defineProperty', 'deleteProperty']

const isA = Array.isArray(target)
const clone = isA ? v => [...v] : v => Object.assign({}, v)

const mutationTrapError = (isA) => {
throw new Error(`${isA ? 'array' : 'object'} is immutable`)
}

const override = prop => (...args) => {
const mutMethod = mutArrMethods.includes(prop)
const nonMutMethod = nonMutArrMethods.includes(prop)
Expand Down Expand Up @@ -35,14 +40,17 @@ function mewt(target) {
throw new Error('mewt accepts array or object')
}

return new Proxy(target, {
set () {
throw new Error(`${isA ? 'array' : 'object'} is immutable`)
},
get (_, prop) {
let proxyHandler = {
get: (_, prop) => {
return api[prop] || target[prop] && ({}.hasOwnProperty.call(target, prop) ? target[prop] : override(prop))
}
}

mutationTraps.forEach((key) => {
proxyHandler[key] = mutationTrapError
})

return new Proxy(target, proxyHandler)
}

module.exports = mewt
2 changes: 1 addition & 1 deletion lib/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,29 @@ describe('mewt', () => {
expect(() => o.track = 'The Promise').toThrowError(/immutable/)
})

it('should throw on Object.defineProperty', () => {
const o = mewt({})
expect(() => {
Object.defineProperty(o, 'foo', {
value: 'bar'
})
}).toThrowError(/immutable/)
})

it('should throw on delete', () => {
const o = mewt({})
expect(() => {
delete o.foo
}).toThrowError(/immutable/)
})

it('should throw on setPrototypeOf', () => {
const o = mewt({})
expect(() => {
Object.setPrototypeOf(o, {bar: 'baz'})
}).toThrowError(/immutable/)
})

it('should have $set & $unset', () => {
const o = mewt({})
assertMewt(o)
Expand Down

0 comments on commit 2529eb4

Please sign in to comment.