From cbc89ece4dee4257269aeb5cc427fe6b885f2113 Mon Sep 17 00:00:00 2001 From: Daniel Lugo Date: Mon, 13 Sep 2021 14:07:16 -0400 Subject: [PATCH] Utility for merging pending puts --- utils/GunSmith/misc.js | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 utils/GunSmith/misc.js diff --git a/utils/GunSmith/misc.js b/utils/GunSmith/misc.js new file mode 100644 index 00000000..064b8387 --- /dev/null +++ b/utils/GunSmith/misc.js @@ -0,0 +1,45 @@ +/** + * @format + */ +// @ts-check + +// TODO: Check if merge() is equivalent to what gun does. But it should be. +const merge = require('lodash/merge') + +/// + +/** + * @param {GunT.ValidDataValue[]} values + * @returns {GunT.ValidDataValue} + */ +const mergePuts = values => { + /** + * @type {GunT.ValidDataValue} + * @example + * x.put({ a: 1 }) + * x.put('yo') + * assertEquals(await x.then(), 'yo') + * x.put({ b: 2 }) + * assertEquals(await x.then(), { a: 1 , b: 2 }) + */ + const lastObjectValue = {} + + /** @type {GunT.ValidDataValue} */ + let finalResult = {} + + for (const val of values) { + if (typeof val === 'object' && val !== null) { + finalResult = {} + merge(lastObjectValue, val) + merge(finalResult, lastObjectValue) + } else { + finalResult = val + } + } + + return finalResult +} + +module.exports = { + mergePuts +}