Created
February 3, 2022 20:34
-
-
Save chrislaughlin/55cd5f6044f0ca5b34316c24469962cf to your computer and use it in GitHub Desktop.
Pattern Matching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flatten from 'flat'; | |
import objPath from 'object-path'; | |
const _matchKeys = (matchOn, matchWith) => { | |
const matchWithPaths = Object.keys(flatten(matchWith)); | |
const matchWithValues = matchWithPaths.map(path => { | |
return objPath.get(matchWith, path); | |
}) | |
const matchOnValues = matchWithPaths.map(path => { | |
return objPath.get(matchOn, path); | |
}) | |
return matchOnValues.every((value, index) => { | |
return value === matchWithValues[index]; | |
}) | |
} | |
const _with = matchOn => (matchWith, onMatch) => { | |
const jsonMatchOn = JSON.stringify(matchOn); | |
const jsonMatchWith = JSON.stringify(matchWith); | |
// If the whole object matches | |
if (jsonMatchOn === jsonMatchWith) { | |
return onMatch(); | |
} | |
if (_matchKeys(matchOn, matchWith)) { | |
return onMatch(); | |
} | |
} | |
const match = (matchOn) => { | |
return { | |
with: _with(matchOn) | |
} | |
} | |
//Main useage | |
const myObj = { | |
name: 'chris' | |
}; | |
match(myObj) | |
.with({name: 'chris'}, () => console.log('matched with Chris')); | |
//matched with Chris | |
match(myObj) | |
.with({name: 'john'}, () => console.log('matched with John')); | |
//no match | |
const myObj1 = { | |
status: '200', | |
response: { | |
data: 'hello drunk world', | |
headers: [ | |
'Content-Type: text/plain' | |
], | |
forward: false, | |
foo: { | |
bar: { | |
baz: 'hello' | |
} | |
} | |
} | |
} | |
match(myObj1).with( | |
{ | |
response: { | |
foo: { | |
bar: { | |
baz: 'hello' | |
} | |
} | |
} | |
}, | |
() => console.log('matched'), | |
); | |
//matched |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment