Last active
May 4, 2023 22:31
-
-
Save gordonbrander/75172d6e0c186b11c2a6 to your computer and use it in GitHub Desktop.
KV: key-value iteration functions for JavaScript
This file contains 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
// KV.js | |
// Hash iteration functions | |
// Set a value on an object at field, returning object. | |
function set(object, key, value) { | |
// Set value on object at key. | |
object[key] = value; | |
// Return object. | |
return object; | |
} | |
exports.set = set; | |
// Similar to Array.reduce, but for objects. | |
function reducekv(object, next, reduction) { | |
var keys = Object.keys(object); | |
for (var i = 0; i < keys.length; i++) | |
reduction = next(reduction, keys[i], object[keys[i]]); | |
return reduction; | |
} | |
exports.reducekv = reducekv; | |
// Similar to Array.filter, but for objects. | |
// Takes an object and a predicate function. Predicate is called with | |
// `key` and `value` for each property on object. | |
// Returns a new object containing keys and values that pass the predicate test. | |
function filterkv(object, predicate) { | |
return reducekv(object, function (out, key, value) { | |
return predicate(key, value) ? set(out, key, value) : out; | |
}, {}); | |
} | |
exports.filterkv = filterkv; | |
// Similar to Array.reject, but for objects. | |
// Takes an object and a predicate function. Predicate is called with | |
// `key` and `value` for each property on object. | |
// Returns a new object containing keys and values that fail the predicate test. | |
function rejectkv(object, predicate) { | |
return reducekv(object, function (out, key, value) { | |
return !predicate(key, value) ? set(out, key, value) : out; | |
}, {}); | |
} | |
exports.rejectkv = rejectkv; | |
// Similar to `Array.map`, but for objects. | |
// Takes an object and a mapping function. Maps each `value` in object, setting | |
// new value at `key` on a new object. | |
// Returns a new object of mapped values. | |
function mapv(object, a2b) { | |
return reducekv(object, function (out, key, value) { | |
return set(out, key, a2b(value)); | |
}, {}); | |
} | |
exports.mapv = mapv; | |
// Basic extend function. | |
function extend(a, b) { | |
return reducekv(b, set, a); | |
} | |
exports.extend = extend; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment