mutator

A function to convert plain javascript object(usually deserialized from JSON) into some class instance


Keywords
mutate, plain, object, dto, model, mutation, prototype, type, class
License
MIT
Install
bower install mutator

Documentation

mutator Bower version NPM version

A function to convert plain javascript object(usually deserialized from JSON) into some class instance

Install

Install using bower:

$ bower install mutator --save

Install using npm:

$ npm install mutator --save

Quick Start

Signature:

function mutate(instance, class, [argument passed to constructor])

In Node.js:

const mutate = require('mutator');

mutate(instance, klass);

In Browser:

mutate(instance, klass);

Environment Support

Mutator works fine in most browsers and Node.js.

For Internet Explorer, prior than IE 11, because of lack of object.__proto__, a hard-copy work around is applied.

Quick Sample

A simple Rect class definition

class Rect
  constructor: (width, height) ->
  	@width = width if width?
  	@height = height if height?
  	
  area: ->
  	@width * @height

rect = new Rect(100, 100) # A rect instance

console.log rect.area() # should print 10000

rectJSON = JSON.stringify(rect) # Serialize the object into JSON

###
{
  "width": 100,
  "height": 100
}
###

rectJSON is usually stored into file or transmitted via ajax call.

When consuming the JSON

mutate = require('mutator')

rectCopy = JSON.parse(rectJSON)

console.log rectCopy.area() # Got error: undefined isn't a function!

rectClone = mutate(rectCopy, Rect)

console.log rectClone == rectCopy # true, they are the same instance
console.log rectCopy.area() # got 10000

License

MIT

NPM download