Skip to content

Repository files navigation

object-dsl

µ functional library to transverse objects using an extendable DSL-like syntax

Installation

$ npm i --save object-dsl

Examples

Simple transformations

importcompilefrom'object-dsl'// Operatorsconstreplace=text=>next=>node=>node.replace('%placeholder%',text)consttoUpper=next=>node=>node.toUpperCase()// DSL specconstdsl={foo: replace('world'),obj: {name: toUpper}}// Compile DSLconstcompiled=compile(dsl)// Run with objectconstresult=compiled({foo: 'hello %placeholder%',obj: {name: 'foobar'}})console.log(result)// { foo: 'hello world', obj: { name: 'FOOBAR' }}

Composition

importcompilefrom'object-dsl'// Operatorsconstreplace=text=>next=>node=>node.replace('%placeholder%',text)consttoUpper=next=>node=>node.toUpperCase()// DSL specconstobj={name: toUpper}constdsl={foo: replace('world'),
obj
}// Compile DSLconstcompiled=compile(dsl)// Run with objectconstresult=compiled({foo: 'hello %placeholder%',obj: {name: 'foobar'}})console.log(result)// { foo: 'hello world', obj: { name: 'FOOBAR' }}

array and map operators

importcompile,{array,map}from'object-dsl'// Operatorsconstreplace=(placeholder,text)=>next=>node=>node.replace(`%${placeholder}%`,text)constphoto=next=>node=>`http://image-server.com/files/${node}`// DSL specconstdsl={names: (array(replace('title','Mr.'))),images: (map(photo))}// Compile DSLconstcompiled=compile(dsl)// Run with objectconstresult=compiled({names: ['%title% John Doe','%title% John Smith'],images: {cover: 'cover.png',back: 'back.png',other: 'other.png'}})console.log(result)/*{ names: [ 'Mr. John Doe', 'Mr. John Smith' ], images: { cover: 'http://image-server.com/files/cover.png', back: 'http://image-server.com/files/back.png', other: 'http://image-server.com/files/other.png' } }*/

Passing state

importcompile,{array,map}from'object-dsl'// Operatorsconstitem=next=>(node,state)=>({path: state.path})// DSL specconstdsl={types: (map(array(item)))}// Compile DSLconstreducer=(state,{ key })=>({path: [...state.path,key]})constinitState={path: ['root']}constcompiled=compile(dsl,reducer,initState)// Run with objectconstobj={types: {type1: [{id: 'type1_1'},{id: 'type1_2'}],type2: [{id: 'type2_1'}]}}constresult=compiled(obj)console.log(result)/*{ types: { type1: [ { path: ["root", "types", "type1", 0] }, { path: ["root", "types", "type1", 1] } ], type2: [ { path: ["root", "types", "type2", 0] } ] }}*/// ---------// withMerge// ---------import{withMerge}from'object-dsl'// Run with objectconstresult=withMerge(compiled)(obj)console.log(result)/*{ types: { type1: [ { id: 'type1_1', path: ["root", "types", "type1", 0] }, { id: 'type1_2', path: ["root", "types", "type1", 1] } ], type2: [ { id: 'type2_1', path: ["root", "types", "type2", 0] } ] }}*/

API

About

µ functional library to transverse objects using a extendable DSL-like syntax

Topics

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages