@@ -2,7 +2,10 @@ var assert = require('assert');
22var delve = require ( '.' ) ;
33
44var obj = {
5+ undef : undefined ,
6+ zero : 0 ,
57 one : 1 ,
8+ n : null ,
69 a : {
710 two : 2 ,
811 b : {
@@ -15,15 +18,22 @@ var obj = {
1518} ;
1619
1720// assert equality of a given path, as dot notation and array.
18- function check ( path , value ) {
19- assert . equal ( delve ( obj , path ) , value ) ;
20- console . log ( ' ✓ delve(obj, "' + path + '")' ) ;
21+ //optional third argument is for default when object is not found
22+ function check ( path , value , def ) {
2123
22- var arr = path . split ( '.' ) ;
23- assert . equal ( delve ( obj , arr ) , value ) ;
24- console . log ( ' ✓ delve(obj, ' + JSON . stringify ( arr ) + ')' ) ;
24+ var out = delve ( obj , path , def ) ;
25+ assert . strictEqual ( out , value , 'delve(obj, "' + path + '") should be ' + value + ', got ' + out ) ;
26+ console . log ( ' ✓ delve(obj, "' + path + '"' + ( def ? ', "' + def + '"' : '' ) + ')' ) ;
27+
28+ if ( path ) {
29+ var arr = path . split ( '.' ) ;
30+ assert . strictEqual ( delve ( obj , arr , def ) , value ) ;
31+ console . log ( ' ✓ delve(obj, ' + JSON . stringify ( arr ) + ( def ? ', "' + def + '"' : '' ) + ')' ) ;
32+ console . log ( ' ✓ delve(obj, ' + JSON . stringify ( arr ) + ')' ) ;
33+ }
2534}
2635
36+ console . log ( "> No Defaults" ) ;
2737check ( '' , undefined ) ;
2838check ( 'one' , obj . one ) ;
2939check ( 'one.two' , undefined ) ;
@@ -34,5 +44,26 @@ check('a.b.three', obj.a.b.three);
3444check ( 'a.b.c' , obj . a . b . c ) ;
3545check ( 'a.b.c.four' , obj . a . b . c . four ) ;
3646
47+ //test defaults
48+ console . log ( "\n> With Defaults" ) ;
49+ check ( '' , 'foo' , 'foo' ) ;
50+ check ( 'undef' , 'foo' , 'foo' ) ;
51+ check ( 'n' , null , 'foo' ) ;
52+ check ( 'zero' , 0 , 'foo' ) ;
53+ check ( 'a.badkey' , 'foo' , 'foo' ) ;
54+ check ( 'a.badkey.anotherbadkey' , 'foo' , 'foo' ) ;
55+
56+ //check undefined key throws an error
57+ assert . throws ( delve . bind ( this , obj , undefined ) ) ;
58+ assert . throws ( delve . bind ( this , obj , undefined , 'foo' ) ) ;
59+
60+ //check undefined obj doesn't throw errors and uses default
61+ var backupObj = obj ;
62+ obj = undefined ;
63+ check ( 'one' , undefined ) ;
64+ check ( 'one' , 'foo' , 'foo' ) ;
65+ obj = backupObj ;
66+
67+
3768console . log ( '✅ Success!' ) ;
3869process . exit ( 0 ) ;
0 commit comments