Permalink
Browse files

implemented and tested

  • Loading branch information...
1 parent 4db89d9 commit 4ea2ebf1a7f86eefaff530d691b120c5147155cc @supershabam committed Jan 18, 2013
Showing with 87 additions and 2 deletions.
  1. +15 −0 index.js
  2. +7 −2 package.json
  3. +65 −0 test/unit.test.coffee
View
@@ -0,0 +1,15 @@
+'use strict';
+
+function jsosort(obj, sortfunction) {
+ var result = {};
+ Object.keys(obj).sort(sortfunction).forEach(function(key) {
+ var value = obj[key];
+ if (Object.prototype.toString.call(value) === '[object Object]') {
+ value = jsosort(value, sortfunction);
+ }
+ result[key] = value;
+ });
+ return result;
+}
+
+module.exports = jsosort;
View
@@ -4,7 +4,7 @@
"description": "sort javascript objects so that their properties iterate in a known order",
"main": "index.js",
"scripts": {
- "test": "mocha"
+ "test": "node_modules/.bin/mocha --compilers .coffee:coffee-script test/unit.test.coffee "
},
"repository": {
"type": "git",
@@ -15,5 +15,10 @@
"object"
],
"author": "Ian Hansen",
- "license": "MIT"
+ "license": "MIT",
+ "devDependencies": {
+ "mocha": "~1.8.1",
+ "coffee-script": "~1.4.0",
+ "chai": "~1.4.2"
+ }
}
View
@@ -0,0 +1,65 @@
+jsosort = require "../"
+chai = require "chai"
+
+chai.should()
+
+describe "simple object", ->
+ objA = {}
+ objB = {}
+
+ objA.value1 = "value1"
+ objA.value2 = "value2"
+ objB.value2 = "value2"
+ objB.value1 = "value1"
+
+ it "should be two equivalent objects", ->
+ objA.should.deep.equal(objB)
+
+ it "should not serialize the same", ->
+ objAStr = JSON.stringify(objA)
+ objBStr = JSON.stringify(objB)
+ objAStr.should.not.equal(objBStr)
+
+ it "should serialize the same after sorting", ->
+ objASort = jsosort(objA);
+ objBSort = jsosort(objB);
+ objASortStr = JSON.stringify(objASort)
+ objBSortStr = JSON.stringify(objBSort)
+
+ objASort.should.deep.equal(objBSort)
+ objASort.should.deep.equal(objA)
+ objASortStr.should.equal(objBSortStr)
+
+describe "deep object", ->
+ objA = {}
+ objB = {}
+
+ objA.subobject = {}
+ objA.subobject.value1 = "value1"
+ objA.subobject.array1 = [1, 2, 3]
+ objA.subobject.number1 = 1.2
+ objA.nullvalue = null
+
+ objB.nullvalue = null
+ objB.subobject = {}
+ objB.subobject.number1 = 1.2
+ objB.subobject.array1 = [1, 2, 3]
+ objB.subobject.value1 = "value1"
+
+ it "should be two equivalent objects", ->
+ objA.should.deep.equal(objB)
+
+ it "should not serialize the same", ->
+ objAStr = JSON.stringify(objA)
+ objBStr = JSON.stringify(objB)
+ objAStr.should.not.equal(objBStr)
+
+ it "should serialize the same after sorting", ->
+ objASort = jsosort(objA);
+ objBSort = jsosort(objB);
+ objASortStr = JSON.stringify(objASort)
+ objBSortStr = JSON.stringify(objBSort)
+
+ objASort.should.deep.equal(objBSort)
+ objASort.should.deep.equal(objA)
+ objASortStr.should.equal(objBSortStr)

0 comments on commit 4ea2ebf

Please sign in to comment.