Last active
August 29, 2015 13:58
-
-
Save colelawrence/10010096 to your computer and use it in GitHub Desktop.
Incrementing object properties
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
// Ensure object obj[prop] = {} | |
function _obj(obj, prop) { | |
if (obj[prop] == null) obj[prop] = {} | |
return obj[prop] | |
} | |
// Ensure number obj[prop] (+= val or = val) | |
function _diff(obj, prop, val) { | |
if (obj[prop] == null) obj[prop] = val | |
else obj[prop] += val | |
} | |
function diff(obj, prop, d) { | |
_diff(obj, prop, d) | |
} | |
function inc(obj, prop) { | |
_diff(obj, prop, 1) | |
} | |
function incOf(obj, prop, prop2) { | |
inc(_obj(obj, prop), prop2) | |
} | |
function incMerge(obj, obj2) { | |
var arr = Object.keys(obj2) | |
arr.forEach(function (prop) { | |
inc(_obj(obj, prop), obj2[prop]) | |
}) | |
} | |
function incMergeOf(obj, obj2, prop) { | |
incMerge(_obj(obj, prop), obj2) | |
} | |
function incEach(obj, arr) { | |
arr.forEach(function (prop2) { | |
inc(obj, prop2) | |
}) | |
} | |
function incEachOf(obj, prop, arr) { | |
incEach(_obj(obj, prop), arr) | |
} | |
function incOfEach(obj, arr, prop2) { | |
arr.forEach(function(prop) { | |
incOf(obj, prop, prop2) | |
}) | |
} | |
function incEachOfEach(obj, arr) { | |
var temp | |
function incIfDifferent(prop) { | |
if (prop !== temp) | |
incOf(obj, prop, temp) | |
} | |
arr.forEach(function (prop2) { | |
temp = prop2 | |
arr.forEach(incIfDifferent) | |
}) | |
} | |
exports.diff = diff | |
exports.inc = inc | |
exports.incOf = incOf | |
exports.incMerge = incMerge | |
exports.incMergeOf = incMergeOf | |
exports.incEach = incEach | |
exports.incEachOf = incEachOf | |
exports.incOfEach = incOfEach | |
exports.incEachOfEach = incEachOfEach |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment