Polymorphism via clojure-style protocols.
JavaScript
Latest commit 6727618 Sep 12, 2015 @airportyh Merge pull request #1 from jimmyhmiller/master
Added better error handling
Permalink
Failed to load latest commit information.
README.md Addition to README. May 16, 2015
index.js Added better error handling Sep 5, 2015
package.json Added git repo. May 16, 2015

README.md

protomorphism

Polymorphism via Clojure-style protocols.

Install

npm install protomorphism

Example

const protocol = require('protomorphism')

// create a new protocol `Pattern`, which requires a
// `matches` function to be implemented
const Pattern = protocol({
  matches: function(pattern, string){
    // returns true if string matches pattern
  }
})

// Make all strings implement pattern by exact matching
Pattern.implementation(String, {
  matches: function(pattern, string){
    return pattern === string
  }
})

// Make all arrays implement pattern by reporting a match
// when the array contains the target string
Pattern.implementation(Array, {
  matches: function(arr, string){
    return arr.indexOf(string) !== -1
  }
})

// Make all regular expressions implement pattern
Pattern.implementation(RegExp, {
  matches: function(regexp, string){
    return !!regexp.test(string)
  }
})

// `Pattern.matches` is the polymorphic
// `matches` function which you can use on
// any object who implements `Pattern`.
const matches = Pattern.matches
const patterns = [
  'README.md',
  'README',
  ['README.md', 'readme.md'],
  /README\.(md|rdoc|txt)/i
]

let matched = patterns.some(function(pattern){
  return matches(pattern, input)
})