extracts merge function into a helper module

This commit is contained in:
Lars Berning 2021-05-27 09:36:03 +02:00
parent 2aafc5f12a
commit 3b6b42ec1a
No known key found for this signature in database
GPG Key ID: 028E73C9E1D8A0B3
3 changed files with 30 additions and 22 deletions

View File

@ -9,7 +9,7 @@ import loglevel from 'loglevel'
import rowerProfiles from '../../config/rowerProfiles.js'
import { createRowingEngine } from './RowingEngine.js'
import { replayRowingSession } from '../tools/RowingRecorder.js'
import { deepMerge } from '../tools/ConfigManager.js'
import { deepMerge } from '../tools/Helper.js'
const log = loglevel.getLogger('RowingEngine.test')
log.setLevel('warn')

View File

@ -5,6 +5,7 @@
Merges the different config files and presents the configuration to the application
*/
import defaultConfig from '../../config/default.config.js'
import { deepMerge } from './Helper.js'
async function getConfig () {
let customConfig
@ -15,27 +16,6 @@ async function getConfig () {
return customConfig !== undefined ? deepMerge(defaultConfig, customConfig.default) : defaultConfig
}
export function deepMerge (...objects) {
const isObject = obj => obj && typeof obj === 'object'
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach(key => {
const pVal = prev[key]
const oVal = obj[key]
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal)
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = deepMerge(pVal, oVal)
} else {
prev[key] = oVal
}
})
return prev
}, {})
}
const config = await getConfig()
export default config

28
app/tools/Helper.js Normal file
View File

@ -0,0 +1,28 @@
'use strict'
/*
Open Rowing Monitor, https://github.com/laberning/openrowingmonitor
Helper functions
*/
// deeply merges any number of objects into a new object
export function deepMerge (...objects) {
const isObject = obj => obj && typeof obj === 'object'
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach(key => {
const pVal = prev[key]
const oVal = obj[key]
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal)
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = deepMerge(pVal, oVal)
} else {
prev[key] = oVal
}
})
return prev
}, {})
}