Last active
July 21, 2017 08:31
-
-
Save paveltimofeev/934b7a76d36f6047c117df509e9b7b51 to your computer and use it in GitHub Desktop.
deepSum.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// passthru all nested 'n' props of 'o', and sum their values | |
function deepSum(o,n) { | |
var c=0; | |
if(_.isObject(o)){_.each(_.keys(o||{}), k => { c+= k===n ? parseInt(o[n])||0 : deepSum(o[k],n);});} | |
return c; | |
} | |
var item = { | |
doc_count: 2, | |
val: { | |
buckets: [{ | |
one: { | |
doc_count: 10, | |
count: 100 | |
}, | |
two: { | |
doc_count: 2 | |
} | |
}, { | |
doc_count: 3 | |
}], | |
doc_count: 4 | |
} | |
} | |
var total = deepSum(item, "doc_count"); | |
console.log("Total 21 === ", total); | |
var fail_path_item = { | |
doc_count: null, | |
val: { | |
buckets: [{ | |
one: { | |
doc_count: [], | |
count: 100, | |
test: { | |
doc_count: function(){ return 1000 } | |
} | |
}, | |
two: { | |
doc_count: "", | |
nested: { | |
doc_count: 5 | |
} | |
} | |
}, { | |
doc_count: "zxc0FF" | |
}], | |
doc_count: 7, | |
undef:{ | |
doc_count: undefined | |
} | |
} | |
} | |
console.log("Total 12 === ", deepSum(fail_path_item, "doc_count")); | |
console.log("Total 15 === ", deepSum({doc_count: "0xF"}, "doc_count")); | |
console.log("Total 0 === ", deepSum({}, "doc_count")); | |
console.log("Total 0 === ", deepSum(null, "doc_count")); | |
console.log("Total 0 === ", deepSum(undefined, "doc_count")); | |
console.log("Total 0 === ", deepSum(NaN, "doc_count")); | |
console.log("Total 0 === ", deepSum(1/0, "doc_count")); | |
console.log("Total 0 === ", deepSum("john", "doc_count")); | |
console.log("Total 0 === ", deepSum("1", "doc_count")); | |
function Obj(){ | |
this.doc_count = 1 | |
} | |
Obj.prototype.createNested = function() { | |
this.prop = { | |
doc_count: 10 | |
} | |
} | |
var objItem = new Obj() | |
objItem.createNested() | |
console.log("Total 11 === ", deepSum( objItem, "doc_count")); | |
class User { | |
constructor( count ) { | |
this.score = count ; | |
this.prevScores = [{ score: count+1 }] | |
} | |
} | |
console.log("Total 201 === ", deepSum( new User(100), "score")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment