Typed Mutations

node v10.24.1
version: 2.0.0
endpointsharetweet
let TypedMutations = require("@liveramp/typed-mutations") let originalObject = { "catCount": 2, "cats": [ { "name": "Fluffy" }, { "name": "Flopsy" }] }
let kv1 = TypedMutations.KeyValues.fromObject(originalObject) // Serialize to string so that object equality is deeply checked and not prone // to reference errors JSON.stringify(kv1.toObject()) == JSON.stringify(originalObject)
// In this example, we'll be silly, and negate the count of cats, as well as only returning // their names as a comma separated string. let kv2 = TypedMutations.KeyValues.fromObject(originalObject).map((value) => { if(typeof value == "number") { return -1 * value; } else { // Types aren't showcased here, but in TS, we are certain that the type of value is // {"name": string} due to refinement return value.map((v) => v.name).join(",") } }) kv2.toObject()
// The above isn't great because the key names are still the same. Well, we thought of that! // Let's throw away the count and just return an array of names. let kv3 = TypedMutations.KeyValues.fromObject(originalObject).flatMap((tuple) => { let [key, value] = tuple if(key == "cats") { // The type of value is fully known here so .name access is safe. return [key, value.map((v) => v.name)] } // Else, we return nothing (drop the data) }) kv3.toObject()
// There are also convenience methods. For instance, simply extracting named keys from an object. let animalNoises = { "cat": "meow", "dog": "woof", "horse": "whinny", "zebra": "probably also a whinny", "bird": "tweet" } // The arguments to pluck are typed - so you can tell if you made a typeo. Your IDE / TSC will complain // if you pass something that is not an existing key of the object. let catAndDogNoises = TypedMutations.KeyValues.fromObject(animalNoises).pluck(["cat", "dog"]).toObject()
Loading…

no comments

    sign in to comment