Skip to content

Commit

Permalink
feat(logic): introduce path-satisfies
Browse files Browse the repository at this point in the history
  • Loading branch information
jackw committed Aug 24, 2020
1 parent 0c88c44 commit 4691202
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/_path-satisfies.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
@import 'path';

/// Returns `true` if the specified object property at given path satisfies the
/// given predicate; `false` otherwise.
///
/// @group logic
/// @param {Function} pred
/// @param {List} path The path to use.
/// @param {Object} map The map to retrieve the nested property from.
/// @return {*} The data at `path` of the supplied object or null.
///
/// @example scss - path
///
/// @function is-positive($n) { @return $n > 0; }
/// $value-is-pos: path-satisfies(is-positive, ('a', 'b'), (a: (b: 2)));
/// @debug $value-is-pos; //=> true

@function path-satisfies($pred, $path, $map) {
$value: path($path, $map);
@return if($value, call(get-function($pred), $value), false);
}
94 changes: 94 additions & 0 deletions test/_path-satisfies.spec.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
@import 'true';
@import '../src/path-satisfies';

@function __path-satisfies-spec-is-positive($n) {
@return $n > 0;
}

@function __path-satisfies-spec-has-key-y($map) {
@return map-has-key($map, 'y');
}

@function __path-satisfies-spec-is-map($map) {
@return type-of($map) == 'map';
}

@include describe('path-satisfies [function]') {
@include it(
'returns true if the specified object path satisfies the given predicate'
) {
@include assert-equal(
path-satisfies(
__path-satisfies-spec-is-positive,
('x', 2, 'y'),
(
x: (
(y: -1),
(y: 1),
),
)
),
true
);
}

@include it('returns false if the specified path does not exist') {
@include assert-equal(
path-satisfies(
__path-satisfies-spec-is-positive,
('x', 'y'),
(
x: (
z: 42,
),
)
),
false
);
}

@include it('handles empty paths by applying pred to data: positive') {
@include assert-equal(
path-satisfies(
__path-satisfies-spec-is-map,
(),
(
x: (
z: 42,
),
)
),
true
);
}

@include it('handles empty paths by applying pred to data: negative') {
@include assert-equal(
path-satisfies(
__path-satisfies-spec-has-key-y,
(),
(
x: (
z: 42,
),
)
),
false
);
}

@include it('returns false otherwise') {
@include assert-equal(
path-satisfies(
__path-satisfies-spec-is-positive,
('x', 'y'),
(
x: (
y: 0,
),
)
),
false
);
}
}

0 comments on commit 4691202

Please sign in to comment.