Skip to content

Commit

Permalink
Fix returning values from Object.prototype
Browse files Browse the repository at this point in the history
closes #21
  • Loading branch information
EvanHahn authored and dougwilson committed Jan 3, 2021
1 parent 674ec3a commit 90c1829
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
5 changes: 5 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
unreleased
==========

* Fix returning values from `Object.prototype`

2.0.0 / 2020-04-19
==================

Expand Down
38 changes: 31 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,34 @@ function createStatusCodeList (codes) {
})
}

/**
* Get the status code for given message.
* @private
*/

function getStatusCode (message) {
var msg = message.toLowerCase()

if (!Object.prototype.hasOwnProperty.call(status.code, msg)) {
throw new Error('invalid status message: "' + message + '"')
}

return status.code[msg]
}

/**
* Get the status message for given code.
* @private
*/

function getStatusMessage (code) {
if (!Object.prototype.hasOwnProperty.call(status.message, code)) {
throw new Error('invalid status code: ' + code)
}

return status.message[code]
}

/**
* Get the status code.
*
Expand All @@ -101,8 +129,7 @@ function createStatusCodeList (codes) {

function status (code) {
if (typeof code === 'number') {
if (!status.message[code]) throw new Error('invalid status code: ' + code)
return status.message[code]
return getStatusMessage(code)
}

if (typeof code !== 'string') {
Expand All @@ -112,11 +139,8 @@ function status (code) {
// '403'
var n = parseInt(code, 10)
if (!isNaN(n)) {
if (!status.message[n]) throw new Error('invalid status code: ' + n)
return status.message[n]
return getStatusMessage(n)
}

n = status.code[code.toLowerCase()]
if (!n) throw new Error('invalid status message: "' + code + '"')
return n
return getStatusCode(code)
}
2 changes: 2 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ describe('status', function () {

it('should throw for unknown status message', function () {
assert.throws(status.bind(null, 'too many bugs'), /invalid status message/)
assert.throws(status.bind(null, 'constructor'), /invalid status message/)
assert.throws(status.bind(null, '__proto__'), /invalid status message/)
})

it('should throw for unknown status code', function () {
Expand Down

0 comments on commit 90c1829

Please sign in to comment.