What is the sum of all numbers in the JSON? (The are no numeric strings in the JSON.)
const input = '{"a":{"b":4},"c":-1}'
const numbers = input.match(/(-?\d+)/g)
const part1 = numbers.reduce((total, number) => total + Number(number), 0)
console.log('Part 1:', part1)
Flems link in Part 2.
Hah, I cheated! My fastest puzzle solution so far. 😜
Ignore objects (and their children) that have any property with the value
"red"
. Do this only for objects, not arrays. What's the sum now?
Guess we'll have to actually parse the JSON:
const json = JSON.parse(input)
const part2 = Object.values(json).reduce(sum, 0)
console.log('Part 2:', part2)
function sum(total, value) {
// Strings can be ignored because there are no numeric strings
if (typeof value === 'string') {
return total
}
if (typeof value === 'number') {
return total + value
}
if (Array.isArray(value)) {
return total + value.reduce(sum, 0)
}
if (typeof value === 'object') {
const values = Object.values(value)
return values.includes('red') ? total : total + values.reduce(sum, 0)
}
throw new Error(`value "${value}" has invalid type "${typeof value}"`)
}
Try out the final code on flems.io
Nothing, this was an easy puzzle. 😌