Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default Value for Reach #66

Merged
merged 1 commit into from
Jul 17, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,12 @@ var flattenedArray = Hoek.flatten(array, target); // results in [4, 5, 1, 2, 3]

Converts an object key chain string to reference

- `options` - optional settings
- `separator` - string to split chain path on, defaults to '.'
- `defaultValue` - value to return if the path or value is not present, default is `undefined`
- `strict` - if `true`, will throw an error on missing member, default is `false`
- `functions` - if `true` allow traversing functions for properties. `false` will throw an error if a function is part of the chain.

```javascript

var chain = 'a.b.c';
Expand Down
2 changes: 1 addition & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ exports.reach = function (obj, chain, options) {

exports.assert(!options.strict || i + 1 === il, 'Missing segment', path[i], 'in reach path ', chain);
exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', path[i], 'in reach path ', chain);
ref = undefined;
ref = options.defaultValue || undefined;
break;
}

Expand Down
13 changes: 12 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,18 @@ describe('Hoek', function () {

done();
});

it('will return a default value if property is not found', function (done) {

expect(Hoek.reach(obj, 'a.b.q', {defaultValue: 'defaultValue'})).to.equal('defaultValue');
done();
});

it('will return a default value if path is not found', function (done) {

expect(Hoek.reach(obj, 'q', {defaultValue: 'defaultValue'})).to.equal('defaultValue');
done();
});
});

describe('#callStack', function () {
Expand Down Expand Up @@ -1336,4 +1348,3 @@ describe('Hoek', function () {
});
});
});