Skip to content

Commit

Permalink
Neater removeUndef() thanks to @achou11
Browse files Browse the repository at this point in the history
  • Loading branch information
gmaclennan committed Aug 23, 2023
1 parent fd2e981 commit 1e99147
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,22 +62,17 @@ then decoding and comparing the two objects - extra values shouldn't be present`
})

/**
* Remove undefined properties (deeply) from an object, by round-tripping to
* JSON. Also handles Buffers via JSON.parse reviver
*
* @param {object} obj
* @return {object}
* */
function stripUndef(obj) {
// Apologies, if I was not so lazy I would write a deep compare function that
// ignores undefined properties, but instead we do it the lazy way and round
// trip to JSON in order to remove undefined properties. Properties that are
// Buffers won't survive the round trip, so we remove them and add them back.
// Messy, but works well enough for tests. Sorry.
const { coreSignatures, identitySignature, ...rest } = obj
const noUndef = JSON.parse(JSON.stringify(rest))
if (coreSignatures) {
noUndef.coreSignatures = coreSignatures
}
if (identitySignature) {
noUndef.identitySignature = identitySignature
}
return noUndef
return JSON.parse(JSON.stringify(obj), (key, value) => {
if (value.type === 'Buffer') {
return Buffer.from(value.data)
}
return value
})
}

0 comments on commit 1e99147

Please sign in to comment.