pax_global_header 0000666 0000000 0000000 00000000064 13075001565 0014514 g ustar 00root root 0000000 0000000 52 comment=26d69c067ed811251fbcde1c331322aef2acd615
genfun-4.0.1/ 0000775 0000000 0000000 00000000000 13075001565 0013000 5 ustar 00root root 0000000 0000000 genfun-4.0.1/.gitignore 0000664 0000000 0000000 00000000036 13075001565 0014767 0 ustar 00root root 0000000 0000000 *~
.nyc_output/
node_modules/
genfun-4.0.1/.tern-project 0000664 0000000 0000000 00000000047 13075001565 0015416 0 ustar 00root root 0000000 0000000 {
"plugins": {
"node": {}
}
}
genfun-4.0.1/.travis.yml 0000664 0000000 0000000 00000000077 13075001565 0015115 0 ustar 00root root 0000000 0000000 language: node_js
sudo: false
node_js:
- "7"
- "6"
- "4"
genfun-4.0.1/CHANGELOG.md 0000664 0000000 0000000 00000002657 13075001565 0014623 0 ustar 00root root 0000000 0000000 # Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [4.0.1](https://github.com/zkat/genfun/compare/v4.0.0...v4.0.1) (2017-04-16)
### Bug Fixes
* **cache:** stop side-effecting cached applicableMethods ([09cee84](https://github.com/zkat/genfun/commit/09cee84))
# [4.0.0](https://github.com/zkat/genfun/compare/v3.2.1...v4.0.0) (2017-04-16)
### Bug Fixes
* **genfun:** make internal properties private ([e855c72](https://github.com/zkat/genfun/commit/e855c72))
* **perf:** short-circuit default methods ([7a9b06b](https://github.com/zkat/genfun/commit/7a9b06b))
### Features
* **addMethod:** default-method shortcut syntax for gf.add ([40a3ebb](https://github.com/zkat/genfun/commit/40a3ebb))
* **genfun:** default method and name opts + default shortcut ([0a40939](https://github.com/zkat/genfun/commit/0a40939))
* **genfun:** now with inheritance! ([74abcc2](https://github.com/zkat/genfun/commit/74abcc2))
* **nextMethod:** arg-based nextMethod calls ([17a0b35](https://github.com/zkat/genfun/commit/17a0b35))
* **noNext:** allow users to disable nextMethod functionality ([cc00d95](https://github.com/zkat/genfun/commit/cc00d95))
### BREAKING CHANGES
* **nextMethod:** next methods are now passed in as arguments. context/callNextMethod/etc are all gone.
genfun-4.0.1/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000022647 13075001565 0015612 0 ustar 00root root 0000000 0000000 # Code of Conduct
## When Something Happens
If you see a Code of Conduct violation, follow these steps:
1. Let the person know that what they did is not appropriate and ask them to stop and/or edit their message(s) or commits.
2. That person should immediately stop the behavior and correct the issue.
3. If this doesnโt happen, or if you're uncomfortable speaking up, [contact the maintainers](#contacting-maintainers).
4. As soon as available, a maintainer will look into the issue, and take [further action (see below)](#further-enforcement), starting with a warning, then temporary block, then long-term repo or organization ban.
When reporting, please include any relevant details, links, screenshots, context, or other information that may be used to better understand and resolve the situation.
**The maintainer team will prioritize the well-being and comfort of the recipients of the violation over the comfort of the violator.** See [some examples below](#enforcement-examples).
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers of this project pledge to making participation in our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, technical preferences, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language.
* Being respectful of differing viewpoints and experiences.
* Gracefully accepting constructive feedback.
* Focusing on what is best for the community.
* Showing empathy and kindness towards other community members.
* Encouraging and raising up your peers in the project so you can all bask in hacks and glory.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances, including when simulated online. The only exception to sexual topics is channels/spaces specifically for topics of sexual identity.
* Trolling, insulting/derogatory comments, and personal or political attacks.
* Public or private harassment, deliberate intimidation, or threats.
* Publishing others' private information, such as a physical or electronic address, without explicit permission. This includes any sort of "outing" of any aspect of someone's identity without their consent.
* Publishing private screenshots or quotes of interactions in the context of this project without all quoted users' *explicit* consent.
* Publishing of private communication that doesn't have to do with reporting harrassment.
* Any of the above even when [presented as "ironic" or "joking"](https://en.wikipedia.org/wiki/Hipster_racism).
* Any attempt to present "reverse-ism" versions of the above as violations. Examples of reverse-isms are "reverse racism", "reverse sexism", "heterophobia", and "cisphobia".
* Unsolicited explanations under the assumption that someone doesn't already know it. Ask before you teach! Don't assume what people's knowledge gaps are.
* [Feigning or exaggerating surprise](https://www.recurse.com/manual#no-feigned-surprise) when someone admits to not knowing something.
* "[Well-actuallies](https://www.recurse.com/manual#no-well-actuallys)"
* Other conduct which could reasonably be considered inappropriate in a professional or community setting.
## Scope
This Code of Conduct applies both within spaces involving this project and in other spaces involving community members. This includes the repository, its Pull Requests and Issue tracker, its Twitter community, private email communications in the context of the project, and any events where members of the project are participating, as well as adjacent communities and venues affecting the project's members.
Depending on the violation, the maintainers may decide that violations of this code of conduct that have happened outside of the scope of the community may deem an individual unwelcome, and take appropriate action to maintain the comfort and safety of its members.
### Other Community Standards
As a project on GitHub, this project is additionally covered by the [GitHub Community Guidelines](https://help.github.com/articles/github-community-guidelines/).
Additionally, as a project hosted on npm, is is covered by [npm, Inc's Code of Conduct](https://www.npmjs.com/policies/conduct).
Enforcement of those guidelines after violations overlapping with the above are the responsibility of the entities, and enforcement may happen in any or all of the services/communities.
## Maintainer Enforcement Process
Once the maintainers get involved, they will follow a documented series of steps and do their best to preserve the well-being of project members. This section covers actual concrete steps.
### Contacting Maintainers
You may get in touch with the maintainer team through any of the following methods:
* Through email:
* [kzm@sykosomatic.org](mailto:kzm@sykosomatic.org) (Kat Marchรกn)
### Further Enforcement
If you've already followed the [initial enforcement steps](#enforcement), these are the steps maintainers will take for further enforcement, as needed:
1. Repeat the request to stop.
2. If the person doubles down, they will have offending messages removed or edited by a maintainers given an official warning. The PR or Issue may be locked.
3. If the behavior continues or is repeated later, the person will be blocked from participating for 24 hours.
4. If the behavior continues or is repeated after the temporary block, a long-term (6-12mo) ban will be used.
On top of this, maintainers may remove any offending messages, images, contributions, etc, as they deem necessary.
Maintainers reserve full rights to skip any of these steps, at their discretion, if the violation is considered to be a serious and/or immediate threat to the health and well-being of members of the community. These include any threats, serious physical or verbal attacks, and other such behavior that would be completely unacceptable in any social setting that puts our members at risk.
Members expelled from events or venues with any sort of paid attendance will not be refunded.
### Who Watches the Watchers?
Maintainers and other leaders who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. These may include anything from removal from the maintainer team to a permanent ban from the community.
Additionally, as a project hosted on both GitHub and npm, [their own Codes of Conducts may be applied against maintainers of this project](#other-community-standards), externally of this project's procedures.
### Enforcement Examples
#### The Best Case
The vast majority of situations work out like this. This interaction is common, and generally positive.
> Alex: "Yeah I used X and it was really crazy!"
> Patt (not a maintainer): "Hey, could you not use that word? What about 'ridiculous' instead?"
> Alex: "oh sorry, sure." -> edits old comment to say "it was really confusing!"
#### The Maintainer Case
Sometimes, though, you need to get maintainers involved. Maintainers will do their best to resolve conflicts, but people who were harmed by something **will take priority**.
> Patt: "Honestly, sometimes I just really hate using $library and anyone who uses it probably sucks at their job."
> Alex: "Whoa there, could you dial it back a bit? There's a CoC thing about attacking folks' tech use like that."
> Patt: "I'm not attacking anyone, what's your problem?"
> Alex: "@maintainers hey uh. Can someone look at this issue? Patt is getting a bit aggro. I tried to nudge them about it, but nope."
> KeeperOfCommitBits: (on issue) "Hey Patt, maintainer here. Could you tone it down? This sort of attack is really not okay in this space."
> Patt: "Leave me alone I haven't said anything bad wtf is wrong with you."
> KeeperOfCommitBits: (deletes user's comment), "@patt I mean it. Please refer to the CoC over at (URL to this CoC) if you have questions, but you can consider this an actual warning. I'd appreciate it if you reworded your messages in this thread, since they made folks there uncomfortable. Let's try and be kind, yeah?"
> Patt: "@keeperofbits Okay sorry. I'm just frustrated and I'm kinda burnt out and I guess I got carried away. I'll DM Alex a note apologizing and edit my messages. Sorry for the trouble."
> KeeperOfCommitBits: "@patt Thanks for that. I hear you on the stress. Burnout sucks :/. Have a good one!"
#### The Nope Case
> PepeTheFrog๐ธ: "Hi, I am a literal actual nazi and I think white supremacists are quite fashionable."
> Patt: "NOOOOPE. OH NOPE NOPE."
> Alex: "JFC NO. NOPE. @keeperofbits NOPE NOPE LOOK HERE"
> KeeperOfCommitBits: "๐ Nope. NOPE NOPE NOPE. ๐ฅ"
> PepeTheFrog๐ธ has been banned from all organization or user repositories belonging to KeeperOfCommitBits.
## Attribution
This Code of Conduct was generated using [WeAllJS Code of Conduct Generator](https://npm.im/weallbehave), which is based on the [WeAllJS Code of
Conduct](https://wealljs.org/code-of-conduct), which is itself based on
[Contributor Covenant](http://contributor-covenant.org), version 1.4, available
at
[http://contributor-covenant.org/version/1/4](http://contributor-covenant.org/version/1/4),
and the LGBTQ in Technology Slack [Code of
Conduct](http://lgbtq.technology/coc.html).
genfun-4.0.1/CONTRIBUTING.md 0000664 0000000 0000000 00000051526 13075001565 0015242 0 ustar 00root root 0000000 0000000 # Contributing
## How do I...
* [Use This Guide](#introduction)?
* Ask or Say Something? ๐ค๐๐ฑ
* [Request Support](#request-support)
* [Report an Error or Bug](#report-an-error-or-bug)
* [Request a Feature](#request-a-feature)
* Make Something? ๐ค๐ฉ๐ฝโ๐ป๐๐ณ
* [Project Setup](#project-setup)
* [Contribute Documentation](#contribute-documentation)
* [Contribute Code](#contribute-code)
* Manage Something โ
๐๐ผ๐๐
* [Provide Support on Issues](#provide-support-on-issues)
* [Label Issues](#label-issues)
* [Clean Up Issues and PRs](#clean-up-issues-and-prs)
* [Review Pull Requests](#review-pull-requests)
* [Merge Pull Requests](#merge-pull-requests)
* [Tag a Release](#tag-a-release)
* [Join the Project Team](#join-the-project-team)
* Add a Guide Like This One [To My Project](#attribution)? ๐ค๐ป๐ป
## Introduction
Thank you so much for your interest in contributing!. All types of contributions are encouraged and valued. See the [table of contents](#toc) for different ways to help and details about how this project handles them!๐
Please make sure to read the relevant section before making your contribution! It will make it a lot easier for us maintainers to make the most of it and smooth out the experience for all involved. ๐
The [Project Team](#join-the-project-team) looks forward to your contributions. ๐๐พโจ
## Request Support
If you have a question about this project, how to use it, or just need clarification about something:
* Open an Issue at https://github.com/zkat/genfun/issues
* Provide as much context as you can about what you're running into.
* Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. If not, please be ready to provide that information if maintainers ask for it.
Once it's filed:
* The project team will [label the issue](#label-issues).
* Someone will try to have a response soon.
* If you or the maintainers don't respond to an issue for 30 days, the [issue will be closed](#clean-up-issues-and-prs). If you want to come back to it, reply (once, please), and we'll reopen the existing issue. Please avoid filing new issues as extensions of one you already made.
## Report an Error or Bug
If you run into an error or bug with the project:
* Open an Issue at https://github.com/zkat/genfun/issues
* Include *reproduction steps* that someone else can follow to recreate the bug or error on their own.
* Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. If not, please be ready to provide that information if maintainers ask for it.
Once it's filed:
* The project team will [label the issue](#label-issues).
* A team member will try to reproduce the issue with your provided steps. If there are no repro steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
* If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#contribute-code).
* If you or the maintainers don't respond to an issue for 30 days, the [issue will be closed](#clean-up-issues-and-prs). If you want to come back to it, reply (once, please), and we'll reopen the existing issue. Please avoid filing new issues as extensions of one you already made.
* `critical` issues may be left open, depending on perceived immediacy and severity, even past the 30 day deadline.
## Request a Feature
If the project doesn't do something you need or want it to do:
* Open an Issue at https://github.com/zkat/genfun/issues
* Provide as much context as you can about what you're running into.
* Please try and be clear about why existing features and alternatives would not work for you.
Once it's filed:
* The project team will [label the issue](#label-issues).
* The project team will evaluate the feature request, possibly asking you more questions to understand its purpose and any relevant requirements. If the issue is closed, the team will convey their reasoning and suggest an alternative path forward.
* If the feature request is accepted, it will be marked for implementation with `feature-accepted`, which can then be done by either by a core team member or by anyone in the community who wants to [contribute code](#contribute-code).
Note: The team is unlikely to be able to accept every single feature request that is filed. Please understand if they need to say no.
## Project Setup
So you wanna contribute some code! That's great! This project uses GitHub Pull Requests to manage contributions, so [read up on how to fork a GitHub project and file a PR](https://guides.github.com/activities/forking) if you've never done it before.
If this seems like a lot or you aren't able to do all this setup, you might also be able to [edit the files directly](https://help.github.com/articles/editing-files-in-another-user-s-repository/) without having to do any of this setup. Yes, [even code](#contribute-code).
If you want to go the usual route and run the project locally, though:
* [Install Node.js](https://nodejs.org/en/download/)
* [Fork the project](https://guides.github.com/activities/forking/#fork)
Then in your terminal:
* `cd path/to/your/clone`
* `npm install`
* `npm test`
And you should be ready to go!
## Contribute Documentation
Documentation is a super important, critical part of this project. Docs are how we keep track of what we're doing, how, and why. It's how we stay on the same page about our policies. And it's how we tell others everything they need in order to be able to use this project -- or contribute to it. So thank you in advance.
Documentation contributions of any size are welcome! Feel free to file a PR even if you're just rewording a sentence to be more clear, or fixing a spelling mistake!
To contribute documentation:
* [Set up the project](#project-setup).
* Edit or add any relevant documentation.
* Make sure your changes are formatted correctly and consistently with the rest of the documentation.
* Re-read what you wrote, and run a spellchecker on it to make sure you didn't miss anything.
* In your commit message(s), begin the first line with `docs: `. For example: `docs: Adding a doc contrib section to CONTRIBUTING.md`.
* Write clear, concise commit message(s) using [conventional-changelog format](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md). Documentation commits should use `docs(): `.
* Go to https://github.com/zkat/genfun/pulls and open a new pull request with your changes.
* If your PR is connected to an open issue, add a line in your PR's description that says `Fixes: #123`, where `#123` is the number of the issue you're fixing.
Once you've filed the PR:
* One or more maintainers will use GitHub's review feature to review your PR.
* If the maintainer asks for any changes, edit your changes, push, and ask for another review.
* If the maintainer decides to pass on your PR, they will thank you for the contribution and explain why they won't be accepting the changes. That's ok! We still really appreciate you taking the time to do it, and we don't take that lightly. ๐
* If your PR gets accepted, it will be marked as such, and merged into the `latest` branch soon after. Your contribution will be distributed to the masses next time the maintainers [tag a release](#tag-a-release)
## Contribute Code
We like code commits a lot! They're super handy, and they keep the project going and doing the work it needs to do to be useful to others.
Code contributions of just about any size are acceptable!
The main difference between code contributions and documentation contributions is that contributing code requires inclusion of relevant tests for the code being added or changed. Contributions without accompanying tests will be held off until a test is added, unless the maintainers consider the specific tests to be either impossible, or way too much of a burden for such a contribution.
To contribute code:
* [Set up the project](#project-setup).
* Make any necessary changes to the source code.
* Include any [additional documentation](#contribute-documentation) the changes might need.
* Write tests that verify that your contribution works as expected.
* Write clear, concise commit message(s) using [conventional-changelog format](https://github.com/conventional-changelog/conventional-changelog-angular/blob/master/convention.md).
* Dependency updates, additions, or removals must be in individual commits, and the message must use the format: `(deps): PKG@VERSION`, where `` is any of the usual `conventional-changelog` prefixes, at your discretion.
* Go to https://github.com/zkat/genfun/pulls and open a new pull request with your changes.
* If your PR is connected to an open issue, add a line in your PR's description that says `Fixes: #123`, where `#123` is the number of the issue you're fixing.
Once you've filed the PR:
* Barring special circumstances, maintainers will not review PRs until all checks pass (Travis, AppVeyor, etc).
* One or more maintainers will use GitHub's review feature to review your PR.
* If the maintainer asks for any changes, edit your changes, push, and ask for another review. Additional tags (such as `needs-tests`) will be added depending on the review.
* If the maintainer decides to pass on your PR, they will thank you for the contribution and explain why they won't be accepting the changes. That's ok! We still really appreciate you taking the time to do it, and we don't take that lightly. ๐
* If your PR gets accepted, it will be marked as such, and merged into the `latest` branch soon after. Your contribution will be distributed to the masses next time the maintainers [tag a release](#tag-a-release)
## Provide Support on Issues
[Needs Collaborator](#join-the-project-team): none
Helping out other users with their questions is a really awesome way of contributing to any community. It's not uncommon for most of the issues on an open source projects being support-related questions by users trying to understand something they ran into, or find their way around a known bug.
Sometimes, the `support` label will be added to things that turn out to actually be other things, like bugs or feature requests. In that case, suss out the details with the person who filed the original issue, add a comment explaining what the bug is, and change the label from `support` to `bug` or `feature`. If you can't do this yourself, @mention a maintainer so they can do it.
In order to help other folks out with their questions:
* Go to the issue tracker and [filter open issues by the `support` label](https://github.com/zkat/genfun/issues?q=is%3Aopen+is%3Aissue+label%3Asupport).
* Read through the list until you find something that you're familiar enough with to give an answer to.
* Respond to the issue with whatever details are needed to clarify the question, or get more details about what's going on.
* Once the discussion wraps up and things are clarified, either close the issue, or ask the original issue filer (or a maintainer) to close it for you.
Some notes on picking up support issues:
* Avoid responding to issues you don't know you can answer accurately.
* As much as possible, try to refer to past issues with accepted answers. Link to them from your replies with the `#123` format.
* Be kind and patient with users -- often, folks who have run into confusing things might be upset or impatient. This is ok. Try to understand where they're coming from, and if you're too uncomfortable with the tone, feel free to stay away or withdraw from the issue. (note: if the user is outright hostile or is violating the CoC, [refer to the Code of Conduct](CODE_OF_CONDUCT.md) to resolve the conflict).
## Label Issues
[Needs Collaborator](#join-the-project-team): Issue Tracker
One of the most important tasks in handling issues is labeling them usefully and accurately. All other tasks involving issues ultimately rely on the issue being classified in such a way that relevant parties looking to do their own tasks can find them quickly and easily.
In order to label issues, [open up the list of unlabeled issues](https://github.com/zkat/genfun/issues?q=is%3Aopen+is%3Aissue+no%3Alabel) and, **from newest to oldest**, read through each one and apply issue labels according to the table below. If you're unsure about what label to apply, skip the issue and try the next one: don't feel obligated to label each and every issue yourself!
Label | Apply When | Notes
--- | --- | ---
`bug` | Cases where the code (or documentation) is behaving in a way it wasn't intended to. | If something is happening that surprises the *user* but does not go against the way the code is designed, it should use the `enhancement` label.
`critical` | Added to `bug` issues if the problem described makes the code completely unusable in a common situation. |
`documentation` | Added to issues or pull requests that affect any of the documentation for the project. | Can be combined with other labels, such as `bug` or `enhancement`.
`duplicate` | Added to issues or PRs that refer to the exact same issue as another one that's been previously labeled. | Duplicate issues should be marked and closed right away, with a message referencing the issue it's a duplicate of (with `#123`)
`enhancement` | Added to [feature requests](#request-a-feature), PRs, or documentation issues that are purely additive: the code or docs currently work as expected, but a change is being requested or suggested. |
`help wanted` | Applied by [Committers](#join-the-project-team) to issues and PRs that they would like to get outside help for. Generally, this means it's lower priority for the maintainer team to itself implement, but that the community is encouraged to pick up if they so desire | Never applied on first-pass labeling.
`in-progress` | Applied by [Committers](#join-the-project-team) to PRs that are pending some work before they're ready for review. | The original PR submitter should @mention the team member that applied the label once the PR is complete.
`performance` | This issue or PR is directly related to improving performance. |
`refactor` | Added to issues or PRs that deal with cleaning up or modifying the project for the betterment of it. |
`starter` | Applied by [Committers](#join-the-project-team) to issues that they consider good introductions to the project for people who have not contributed before. These are not necessarily "easy", but rather focused around how much context is necessary in order to understand what needs to be done for this project in particular. | Existing project members are expected to stay away from these unless they increase in priority.
`support` | This issue is either asking a question about how to use the project, clarifying the reason for unexpected behavior, or possibly reporting a `bug` but does not have enough detail yet to determine whether it would count as such. | The label should be switched to `bug` if reliable reproduction steps are provided. Issues primarily with unintended configurations of a user's environment are not considered bugs, even if they cause crashes.
`tests` | This issue or PR either requests or adds primarily tests to the project. | If a PR is pending tests, that will be handled through the [PR review process](#review-pull-requests)
`wontfix` | Labelers may apply this label to issues that clearly have nothing at all to do with the project or are otherwise entirely outside of its scope/sphere of influence. [Committers](#join-the-project-team) may apply this label and close an issue or PR if they decide to pass on an otherwise relevant issue. | The issue or PR should be closed as soon as the label is applied, and a clear explanation provided of why the label was used. Contributors are free to contest the labeling, but the decision ultimately falls on committers as to whether to accept something or not.
## Clean Up Issues and PRs
[Needs Collaborator](#join-the-project-team): Issue Tracker
Issues and PRs can go stale after a while. Maybe they're abandoned. Maybe the team will just plain not have time to address them any time soon.
In these cases, they should be closed until they're brought up again or the interaction starts over.
To clean up issues and PRs:
* Search the issue tracker for issues or PRs, and add the term `updated:<=YYYY-MM-DD`, where the date is 30 days before today.
* Go through each issue *from oldest to newest*, and close them if **all of the following are true**:
* not opened by a maintainer
* not marked as `critical`
* not marked as `starter` or `help wanted` (these might stick around for a while, in general, as they're intended to be available)
* no explicit messages in the comments asking for it to be left open
* does not belong to a milestone
* Leave a message when closing saying "Cleaning up stale issue. Please reopen or ping us if and when you're ready to resume this. See https://github.com/zkat/genfun/blob/latest/CONTRIBUTING.md#clean-up-issues-and-prs for more details."
## Review Pull Requests
[Needs Collaborator](#join-the-project-team): Issue Tracker
While anyone can comment on a PR, add feedback, etc, PRs are only *approved* by team members with Issue Tracker or higher permissions.
PR reviews use [GitHub's own review feature](https://help.github.com/articles/about-pull-request-reviews/), which manages comments, approval, and review iteration.
Some notes:
* You may ask for minor changes ("nitpicks"), but consider whether they are really blockers to merging: try to err on the side of "approve, with comments".
* *ALL PULL REQUESTS* should be covered by a test: either by a previously-failing test, an existing test that covers the entire functionality of the submitted code, or new tests to verify any new/changed behavior. All tests must also pass and follow established conventions. Test coverage should not drop, unless the specific case is considered reasonable by maintainers.
* Please make sure you're familiar with the code or documentation being updated, unless it's a minor change (spellchecking, minor formatting, etc). You may @mention another project member who you think is better suited for the review, but still provide a non-approving review of your own.
* Be extra kind: people who submit code/doc contributions are putting themselves in a pretty vulnerable position, and have put time and care into what they've done (even if that's not obvious to you!) -- always respond with respect, be understanding, but don't feel like you need to sacrifice your standards for their sake, either. Just don't be a jerk about it?
## Merge Pull Requests
[Needs Collaborator](#join-the-project-team): Committer
TBD - need to hash out a bit more of this process.
## Tag A Release
[Needs Collaborator](#join-the-project-team): Committer
TBD - need to hash out a bit more of this process. The most important bit here is probably that all tests must pass, and tags must use [semver](https://semver.org).
## Join the Project Team
### Ways to Join
There are many ways to contribute! Most of them don't require any official status unless otherwise noted. That said, there's a couple of positions that grant special repository abilities, and this section describes how they're granted and what they do.
All of the below positions are granted based on the project team's needs, as well as their consensus opinion about whether they would like to work with the person and think that they would fit well into that position. The process is relatively informal, and it's likely that people who express interest in participating can just be granted the permissions they'd like.
You can spot a collaborator on the repo by looking for the `[Collaborator]` or `[Owner]` tags next to their names.
Permission | Description
--- | ---
Issue Tracker | Granted to contributors who express a strong interest in spending time on the project's issue tracker. These tasks are mainly [labeling issues](#label-issues), [cleaning up old ones](#clean-up-issues-and-prs), and [reviewing pull requests](#review-pull-requests), as well as all the usual things non-team-member contributors can do. Issue handlers should not merge pull requests, tag releases, or directly commit code themselves: that should still be done through the usual pull request process. Becoming an Issue Handler means the project team trusts you to understand enough of the team's process and context to implement it on the issue tracker.
Committer | Granted to contributors who want to handle the actual pull request merges, tagging new versions, etc. Committers should have a good level of familiarity with the codebase, and enough context to understand the implications of various changes, as well as a good sense of the will and expectations of the project team.
Admin/Owner | Granted to people ultimately responsible for the project, its community, etc.
## Attribution
This guide was generated using the WeAllJS `CONTRIBUTING.md` generator. [Make your own](https://npm.im/weallcontribute)!
genfun-4.0.1/README.md 0000664 0000000 0000000 00000015654 13075001565 0014272 0 ustar 00root root 0000000 0000000 # Genfun [](https://travis-ci.org/zkat/genfun) [](https://npm.im/genfun) [](https://npm.im/genfun)
[`genfun`](https://github.com/zkat/genfun) is a Javascript library that lets you
define generic functions: regular-seeming functions that can be invoked just
like any other function, but that automatically dispatch methods based on the
combination of arguments passed to it when it's called, also known as multiple
dispatch.
It was inspired by [Slate](http://slatelanguage.org/),
[CLOS](http://en.wikipedia.org/wiki/CLOS) and
[Sheeple](http://github.com/zkat/sheeple).
## Install
`$ npm install genfun`
## Table of Contents
* [Example](#example)
* [API](#api)
* [`Genfun()`](#genfun)
* [`gf.add()`](#addMethod)
* [`Genfun.callNextMethod()`](#callNextMethod)
* [`Genfun.noApplicableMethod()`](#noApplicableMethod)
* [Performance](#performance)
### Example
Various examples are available to look at in the examples/ folder included in
this project. Most examples are also runnable by just invoking them with node.
```javascript
import Genfun from "genfun"
class Person {}
class Dog {}
const frobnicate = Genfun()
frobnicate.add([Person], (person) => {
console.log('Got a person!')
})
frobnicate.add([Dog], (dog) => {
console.log('Got a dog!')
})
frobnicate.add([String, Person, Dog], (greeting, person, dog) => {
console.log(person, ' greets ', dog, ', \'' + greeting + '\'')
})
const person = new Person()
const dog = new Dog()
frobnicate(person) // Got a person!
frobnicate(dog) // Got a dog!
frobnicate('Hi, dog!', person, dog); // {} greets {}, 'Hi, dog!'
```
### API
The basic API for `Genfun` is fairly simple: You create a new `genfun` by
calling `Genfun()`, and add methods to them. Then you call the `genfun` object
like a regular function, and it takes care of dispatching the appropriate
methods!
#### `Genfun()`
Takes no arguments. Simply creates a new `genfun`. A `genfun` is a regular
function object with overriden function call/dispatch behavior.
When called, it will look at its arguments and determine if a matching method
has been defined that applies to **all** arguments passed in, considered
together.
New methods may be added to the `genfun` object with [`gf.add()`](#addMethod).
If no method is found, or none has been defined, it will invoke
[`Genfun.noApplicableMethod`](#noApplicableMethod) with the appropriate
arguments.
Genfuns preserve the value of `this` if invoked using `.call` or `.apply`.
##### Example
```javascript
var gf = Genfun()
//... add some methods ..
// These calls are all identical.
gf(1, 2, 3)
gf.call(null, 1, 2, 3)
gf.apply(null, [1, 2, 3])
```
#### `gf.add(, )`
Adds a new method to `gf` and returns `gf` to allow chaining multiple `add`s.
`` must be an array of objects that will receive new `Role`s (dispatch
positions) for the method. If an object in the selector is a function, its
`.prototype` field will receive the new `Role`. The array must not contain any
frozen objects.
When a `genfun` is called (like a function), it will look at its set of added
methods and, based on the `Role`s assigned, and corresponding prototype chains,
will determine which method, if any, will be invoked. On invocation, a method's
`` argument will be the called with the arguments passed to the `genfun`,
including its `this` and `arguments` values`.
Within the ``, [`Genfun.callNextMethod`](#callNextMethod) may be called.
##### Example
```javascript
var numStr = Genfun()
numStr.add([String, Number], function (str, num) {
console.log('got a str:', str, 'and a num: ', num)
})
numStr.add([Number, String], function (num, str) {
console.log('got a num:', num, 'and a str:', str)
})
```
#### `Genfun.callNextMethod([...])`
**NOTE**: This function can only be called synchronously. To call it
asynchronously (for example, in a `Promise` or in a callback), use
[`getContext`](#getContext)
Calls the "next" applicable method in the method chain. Can only be called
within the body of a method.
If no arguments are given, `callNextMethod` will pass the current method's
original arguments to the next method.
If arguments are passed to `callNextMethod`, it will invoke the next applicable
method (based on the **original** method list calculation), with **the given
arguments**, even if they would otherwise not have triggered that method.
Returns whatever value the next method returns.
There **must** be a next method available when invoked. This function **will
not** call `noApplicableMethod` when it runs out of methods to call. It will
instead throw an error.
##### Example
```javascript
class Foo {}
class Bar extends Foo {}
var cnm = Genfun()
cnm.add([Foo], function (foo) {
console.log('calling the method on Foo with', foo)
return foo
})
cnm.add([Bar], function (bar) {
console.log('calling the method on Bar with', bar)
return Genfun.callNextMethod('some other value!')
})
cnm(new Bar())
// calling the method on Bar with {}
// calling the method on Foo with "some other value!"
// => 'some other value!'
```
#### `Genfun.getContext()`
The `context` returned by this function will have a `callNextMethod` method
which can be used to invoke the correct next method even during asynchronous
calls (for example, when used in a callback or a `Promise`).
This function must be called synchronously within the body of the method before
any asynchronous calls, and will error if invoked outside the context of a
method call.
##### Example
```javascript
someGenfun.add([MyThing], function (thing) {
const ctx = Genfun.getContext()
return somePromisedCall(thing).then(res => ctx.callNextMethod(res))
})
```
#### `Genfun.noApplicableMethod(, , )`
`Genfun.noApplicableMethod` is a `genfun` itself, which is called whenever **any `genfun`** fails to find a matching method for its given arguments.
It will be called with the `genfun` as its first argument, then the `this`
value, and then the arguments it was called with.
By default, this will simply throw a NoApplicableMethod error.
Users may override this behavior for particular `genfun` and `this`
combinations, although `args` will always be an `Array`. The value returned from
the dispatched `noApplicableMethod` method will be returned by `genfun` as if it
had been its original method. Comparable to [Ruby's
`method_missing`](http://ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing).
### Performance
`Genfun` pulls a few caching tricks to make sure dispatch, specially for common
cases, is as fast as possible.
How fast? Well, not much slower than native methods:
```
Regular function: 30.402ms
Native method: 28.109ms
Singly-dispatched genfun: 64.467ms
Double-dispatched genfun: 70.052ms
Double-dispatched genfun with string primitive: 76.742ms
```
genfun-4.0.1/appveyor.yml 0000664 0000000 0000000 00000000513 13075001565 0015367 0 ustar 00root root 0000000 0000000 environment:
matrix:
- nodejs_version: "7"
- nodejs_version: "6"
- nodejs_version: "4"
platform:
- x64
install:
- ps: Install-Product node $env:nodejs_version $env:platform
- npm config set spin false
- npm i -g npm@latest
- npm install
test_script:
- npm test
matrix:
fast_finish: true
build: off
genfun-4.0.1/bench.js 0000664 0000000 0000000 00000003550 13075001565 0014420 0 ustar 00root root 0000000 0000000 const genfun = require('./')
/*
* Test setup
*/
function TestObj () {}
const testObj = new TestObj()
/*
* Tests
*/
function testFunction (testObj) {
return testObj.toString() + 'test'
}
bench('Regular function', function () {
return testFunction(testObj)
})
TestObj.prototype.testMethod = function () {
return this.toString() + 'test'
}
bench('Native method', function () {
return testObj.testMethod()
})
bench('Applied native method', function () {
return TestObj.prototype.testMethod.apply(testObj, [])
})
testObj.methodGf = genfun(TestObj.prototype.testMethod)
bench('Native-method-style genfun', function () {
return testObj.methodGf()
})
const defaultGenfun = genfun(function (test) {
return testObj.toString() + 'test'
})
bench('Default-dispatched genfun', function () {
return defaultGenfun(testObj)
})
const singleGenfun = genfun()
singleGenfun.add([TestObj], function (testObj) {
return testObj.toString() + 'test'
})
bench('Singly-dispatched genfun', function () {
return singleGenfun(testObj)
})
const doubleGenfun = genfun()
doubleGenfun.add([TestObj, TestObj], function (testObj1, testObj2) {
return testObj.toString() + 'test'
})
bench('Double-dispatched genfun', function () {
return doubleGenfun(testObj, testObj)
})
const doubleString = genfun()
doubleString.add([TestObj, String], function (testObj1, string) {
return testObj.toString() + string
})
bench('Double-dispatched genfun with string primitive', function () {
return doubleString(testObj, 'test')
})
/*
* Util
*/
function bench (name, func, iterations) {
iterations = iterations || 100000
console.time(name)
let val
for (let i = 0; i < iterations; i++) {
val = func() + 'a'
}
console.timeEnd(name)
// This whole dance is solely for the sake of defeating smartass compilers
if (val !== '[object Object]testa') {
throw new Error('got a bad value:', val)
}
}
genfun-4.0.1/examples/ 0000775 0000000 0000000 00000000000 13075001565 0014616 5 ustar 00root root 0000000 0000000 genfun-4.0.1/examples/basic.js 0000664 0000000 0000000 00000002371 13075001565 0016240 0 ustar 00root root 0000000 0000000 var genfun = require("../")
var frobnicate = genfun()
frobnicate.add([String, Number], function (string, number) {
console.log('Got a string and a number')
})
frobnicate.add([Number, String], function (number, string) {
console.log('Got a number and a string')
})
/* Genfun can handle multiple-arity dispatch. Any extra arguments will be
ranked as if the position had been specialized on Object.prototype */
frobnicate.add(
[Number], // Equivalent to [Number, Object]
// when called with two arguments.
function (number) {
console.log('Got a single number.')
})
/* multi-arity dispatch can be exploited to define a 'default' methods */
frobnicate.add([], function () {
console.log('Dispatch fell through to the default method.')
})
/* Empty positions in the dispatch spec will be treated as Object */
frobnicate.add([Number, , Boolean], function (a, b, c) {
console.log('Got a number, ', b, ', and a boolean')
})
frobnicate(new String('foo'), new Number(1)) // => Got a string and a number
frobnicate(1, 'foo') // => Got a number and a string
frobnicate(1) // => Got a single number
frobnicate(1, 1) // => Got a single number
frobnicate(true) // => Dispatch fell through
frobnicate(1, [], true) // => Got a number, [], and a boolean
genfun-4.0.1/examples/fmap.js 0000664 0000000 0000000 00000005402 13075001565 0016100 0 ustar 00root root 0000000 0000000 var genfun = require('../')
/*
* This file implements an approximation of the Functor instances described
* in the Haskell wikibook:
*
* https://en.wikibooks.org/wiki/Haskell/The_Functor_class
*/
/**
* Generic function used in the Functor typeclass we're simulating in this
* file. The typeclass can be instantiated by simply adding the appropriate
* methods to fmap, which follow the Functor laws:
*
* `fmap(identity, value) => value`
* `fmap(compose(f, g), value) => f(g(value))`
*
* And for the sake of JavaScript's `this` we add an additional expectation:
* `thing.fmap(function() { return this }, value) => thing`
*
* @param {function} f - Function to map over the value.
* @param {*} value - Value to map over.
*/
var fmap = genfun()
/*
* Default method
*/
fmap.add([], function (f, value) {
throw new Error('No instance of (Functor ' +
Object.prototype.toString.call(value) + ')' +
' arising from use of `fmap`')
})
/*
* Maybe
*/
function Just (value) {
this.value = value
}
var Nothing = {}
fmap.add([Function, Just], function (f, just) {
return new Just(f.call(this, just.value))
})
fmap.add([Function, Nothing], function () {
return Nothing
})
/*
* Array
*/
fmap.add([Function, Array], function (f, array) {
return array.map(f, this)
})
/*
* Tree
*/
function Leaf (value) {
this.value = value
}
function Branch (left, right) {
this.left = left
this.right = right
}
fmap.add([Function, Leaf], function (f, leaf) {
return new Leaf(f.call(this, leaf.value))
})
fmap.add([Function, Branch], function (f, branch) {
return new Branch(fmap.call(this, f, branch.left),
fmap.call(this, f, branch.right))
})
function runExample () {
function logValue (type) {
return function (val) {
console.log('Mapping over ', val, ' in object of type ' + type)
}
}
console.log('Testing Maybe')
fmap(logValue('Just'), new Just(1))
fmap(logValue('Nothing'), Nothing)
console.log('-----------------')
console.log('Testing Array')
fmap(logValue('Array'), [1,2,3])
console.log('-----------------')
console.log('Testing Tree')
function br(a, b) { return new Branch(a, b) }
function lf(x) { return new Leaf(x) }
fmap(logValue('Tree'),
br(
br(
lf(1),
lf(2)),
br(
br(
lf(3),
br(
lf(4),
lf(5))),
lf(6))))
console.log('-----------------')
console.log('Testing default')
try {
fmap(logValue('Fail'), 'Some random string')
} catch(e) {
console.log('Caught expected exception: ', e)
}
}
exports.runExample = runExample
exports.fmap = fmap
if (module.id === '.') runExample()
genfun-4.0.1/examples/hellodog.js 0000664 0000000 0000000 00000001126 13075001565 0016751 0 ustar 00root root 0000000 0000000 var genfun = require('../')
function Person () {}
function Dog () {}
var frobnicate = genfun()
frobnicate.add([Person], function (person) {
console.log('Got a person!')
})
frobnicate.add([Dog], function (dog) {
console.log('Got a dog!')
})
frobnicate.add([String, Person, Dog], function (greeting, person, dog) {
console.log(person, ' greets ', dog, ', "' + greeting + '"')
})
exports.runExample = function () {
var person = new Person()
var dog = new Dog()
frobnicate(person)
frobnicate(dog)
frobnicate('Hi, dog!', person, dog)
}
if (module.id === '.') exports.runExample()
genfun-4.0.1/examples/namespaced_tostring.js 0000664 0000000 0000000 00000001772 13075001565 0021214 0 ustar 00root root 0000000 0000000 var genfun = require('../')
var logs = { toString: genfun(), name: 'logs' }
var json = { toString: genfun(), name: 'json' }
var xml = { toString: genfun(), name: 'xml' }
logs.toString.add([Array], function (array) {
// We can still call regular JS methods on these things...
return '!!! Data (type ' + ({}).toString.call(array) + '): ' + array.toString()
})
json.toString.add([Array], function (array) {
return JSON.stringify(array)
})
xml.toString.add([Array], function (array) {
return '' +
array.reduce(function (acc, next) {
return acc + '' + next.toString() + ''
}, '') + ''
})
exports.runExample = function () {
var array = ['foo', 1, 1.5]
console.log('All the different ways that an Array can be stringified: ')
var formatters = [logs, json, xml]
formatters.forEach(function (module) {
console.log(module.name + '.toString: "' + module.toString(array) + '"')
})
}
if (module.id === '.') exports.runExample()
genfun-4.0.1/lib/ 0000775 0000000 0000000 00000000000 13075001565 0013546 5 ustar 00root root 0000000 0000000 genfun-4.0.1/lib/genfun.js 0000664 0000000 0000000 00000020627 13075001565 0015375 0 ustar 00root root 0000000 0000000 'use strict'
const Method = require('./method')
const Role = require('./role')
const util = require('./util')
const kCache = Symbol('cache')
const kDefaultMethod = Symbol('defaultMethod')
const kMethods = Symbol('methods')
const kNoNext = Symbol('noNext')
module.exports = function genfun (opts) {
function gf () {
if (!gf[kMethods].length && gf[kDefaultMethod]) {
return gf[kDefaultMethod].func.apply(this, arguments)
} else {
return gf.applyGenfun(this, arguments)
}
}
Object.setPrototypeOf(gf, Genfun.prototype)
gf[kMethods] = []
gf[kCache] = {key: [], methods: [], state: STATES.UNINITIALIZED}
if (opts && typeof opts === 'function') {
gf.add(opts)
} else if (opts && opts.default) {
gf.add(opts.default)
}
if (opts && opts.name) {
Object.defineProperty(gf, 'name', {
value: opts.name
})
}
if (opts && opts.noNextMethod) {
gf[kNoNext] = true
}
return gf
}
class Genfun extends Function {}
Genfun.prototype.isGenfun = true
const STATES = {
UNINITIALIZED: 0,
MONOMORPHIC: 1,
POLYMORPHIC: 2,
MEGAMORPHIC: 3
}
const MAX_CACHE_SIZE = 32
/**
* Defines a method on a generic function.
*
* @function
* @param {Array-like} selector - Selector array for dispatching the method.
* @param {Function} methodFunction - Function to execute when the method
* successfully dispatches.
*/
Genfun.prototype.add = function addMethod (selector, func) {
if (!func && typeof selector === 'function') {
func = selector
selector = []
}
selector = [].slice.call(selector)
for (var i = 0; i < selector.length; i++) {
if (!selector.hasOwnProperty(i)) {
selector[i] = Object.prototype
}
}
this[kCache] = {key: [], methods: [], state: STATES.UNINITIALIZED}
let method = new Method(this, selector, func)
if (selector.length) {
this[kMethods].push(method)
} else {
this[kDefaultMethod] = method
}
return this
}
/**
* Removes a previously-defined method on `genfun` that matches
* `selector` exactly.
*
* @function
* @param {Genfun} genfun - Genfun to remove a method from.
* @param {Array-like} selector - Objects to match on when finding a
* method to remove.
*/
Genfun.prototype.rm = function removeMethod () {
throw new Error('not yet implemented')
}
/**
* Returns true if there are methods that apply to the given arguments on
* `genfun`. Additionally, makes sure the cache is warmed up for the given
* arguments.
*
*/
Genfun.prototype.hasMethod = function hasMethod () {
const methods = this.getApplicableMethods(arguments)
return !!(methods && methods.length)
}
/**
* This generic function is called when `genfun` has been called and no
* applicable method was found. The default method throws an `Error`.
*
* @function
* @param {Genfun} genfun - Generic function instance that was called.
* @param {*} newthis - value of `this` the genfun was called with.
* @param {Array} callArgs - Arguments the genfun was called with.
*/
module.exports.noApplicableMethod = module.exports()
module.exports.noApplicableMethod.add([], (gf, thisArg, args) => {
let msg =
'No applicable method found when called with arguments of types: (' +
[].map.call(args, (arg) => {
return (/\[object ([a-zA-Z0-9]+)\]/)
.exec(({}).toString.call(arg))[1]
}).join(', ') + ')'
let err = new Error(msg)
err.genfun = gf
err.thisArg = thisArg
err.args = args
throw err
})
/*
* Internal
*/
Genfun.prototype.applyGenfun = function applyGenfun (newThis, args) {
let applicableMethods = this.getApplicableMethods(args)
if (applicableMethods.length === 1 || this[kNoNext]) {
return applicableMethods[0].func.apply(newThis, args)
} else if (applicableMethods.length > 1) {
let idx = 0
const nextMethod = function nextMethod () {
if (arguments.length) {
// Replace args if passed in explicitly
args = arguments
Array.prototype.push.call(args, nextMethod)
}
const next = applicableMethods[idx++]
if (idx >= applicableMethods.length) {
Array.prototype.pop.call(args)
}
return next.func.apply(newThis, args)
}
Array.prototype.push.call(args, nextMethod)
return nextMethod()
} else {
return module.exports.noApplicableMethod(this, newThis, args)
}
}
Genfun.prototype.getApplicableMethods = function getApplicableMethods (args) {
if (!args.length || !this[kMethods].length) {
return this[kDefaultMethod] ? [this[kDefaultMethod]] : []
}
let applicableMethods
let maybeMethods = cachedMethods(this, args)
if (maybeMethods) {
applicableMethods = maybeMethods
} else {
applicableMethods = computeApplicableMethods(this, args)
cacheArgs(this, args, applicableMethods)
}
return applicableMethods
}
function cacheArgs (genfun, args, methods) {
if (genfun[kCache].state === STATES.MEGAMORPHIC) { return }
var key = []
var proto
for (var i = 0; i < args.length; i++) {
proto = cacheableProto(genfun, args[i])
if (proto) {
key[i] = proto
} else {
return null
}
}
genfun[kCache].key.unshift(key)
genfun[kCache].methods.unshift(methods)
if (genfun[kCache].key.length === 1) {
genfun[kCache].state = STATES.MONOMORPHIC
} else if (genfun[kCache].key.length < MAX_CACHE_SIZE) {
genfun[kCache].state = STATES.POLYMORPHIC
} else {
genfun[kCache].state = STATES.MEGAMORPHIC
}
}
function cacheableProto (genfun, arg) {
var dispatchable = util.dispatchableObject(arg)
if (Object.hasOwnProperty.call(dispatchable, Role.roleKeyName)) {
for (var j = 0; j < dispatchable[Role.roleKeyName].length; j++) {
var role = dispatchable[Role.roleKeyName][j]
if (role.method.genfun === genfun) {
return null
}
}
}
return Object.getPrototypeOf(dispatchable)
}
function cachedMethods (genfun, args) {
if (genfun[kCache].state === STATES.UNINITIALIZED ||
genfun[kCache].state === STATES.MEGAMORPHIC) {
return null
}
var protos = []
var proto
for (var i = 0; i < args.length; i++) {
proto = cacheableProto(genfun, args[i])
if (proto) {
protos[i] = proto
} else {
return
}
}
for (i = 0; i < genfun[kCache].key.length; i++) {
if (matchCachedMethods(genfun[kCache].key[i], protos)) {
return genfun[kCache].methods[i]
}
}
}
function matchCachedMethods (key, protos) {
if (key.length !== protos.length) { return false }
for (var i = 0; i < key.length; i++) {
if (key[i] !== protos[i]) {
return false
}
}
return true
}
function computeApplicableMethods (genfun, args) {
args = [].slice.call(args)
let discoveredMethods = []
function findAndRankRoles (object, hierarchyPosition, index) {
var roles = Object.hasOwnProperty.call(object, Role.roleKeyName)
? object[Role.roleKeyName]
: []
roles.forEach(role => {
if (role.method.genfun === genfun && index === role.position) {
if (discoveredMethods.indexOf(role.method) < 0) {
Method.clearRank(role.method)
discoveredMethods.push(role.method)
}
Method.setRankHierarchyPosition(role.method, index, hierarchyPosition)
}
})
// When a discovered method would receive more arguments than
// were specialized, we pretend all extra arguments have a role
// on Object.prototype.
if (util.isObjectProto(object)) {
discoveredMethods.forEach(method => {
if (method.minimalSelector <= index) {
Method.setRankHierarchyPosition(method, index, hierarchyPosition)
}
})
}
}
args.forEach((arg, index) => {
getPrecedenceList(util.dispatchableObject(arg))
.forEach((obj, hierarchyPosition) => {
findAndRankRoles(obj, hierarchyPosition, index)
})
})
let applicableMethods = discoveredMethods.filter(method => {
return (args.length === method._rank.length &&
Method.isFullySpecified(method))
})
applicableMethods.sort((a, b) => Method.score(a) - Method.score(b))
if (genfun[kDefaultMethod]) {
applicableMethods.push(genfun[kDefaultMethod])
}
return applicableMethods
}
/*
* Helper function for getting an array representing the entire
* inheritance/precedence chain for an object by navigating its
* prototype pointers.
*/
function getPrecedenceList (obj) {
var precedenceList = []
var nextObj = obj
while (nextObj) {
precedenceList.push(nextObj)
nextObj = Object.getPrototypeOf(nextObj)
}
return precedenceList
}
genfun-4.0.1/lib/method.js 0000664 0000000 0000000 00000004560 13075001565 0015371 0 ustar 00root root 0000000 0000000 'use strict'
/*
* Method
*
* Methods are added, conceptually, to Genfuns, not to objects
* themselves, although the Genfun object does not have any pointers to
* method objects.
*
* The _rank vector is an internal datastructure used during dispatch
* to figure out whether a method is applicable, and if so, how to
* order multiple discovered methods.
*
* Right now, the score method on Method does not take into account any
* ordering, and all arguments to a method are ranked equally for the
* sake of ordering.
*
*/
const Role = require('./role')
const util = require('./util')
module.exports = Method
function Method (genfun, selector, func) {
var method = this
method.genfun = genfun
method.func = func
method._rank = []
method.minimalSelector = 0
const tmpSelector = selector.length ? selector : [Object.prototype]
for (var object, i = tmpSelector.length - 1; i >= 0; i--) {
object = Object.hasOwnProperty.call(tmpSelector, i)
? tmpSelector[i]
: Object.prototype
object = util.dispatchableObject(object)
if (
typeof object === 'function' &&
!object.isGenfun
) {
object = object.prototype
}
if (i > 0 &&
!method.minimalSelector &&
util.isObjectProto(object)) {
continue
} else {
method.minimalSelector++
if (!Object.hasOwnProperty.call(object, Role.roleKeyName)) {
if (Object.defineProperty) {
// Object.defineProperty is JS 1.8.0+
Object.defineProperty(
object, Role.roleKeyName, {value: [], enumerable: false})
} else {
object[Role.roleKeyName] = []
}
}
// XXX HACK - no method replacement now, so we just shove
// it in a place where it'll always show up first. This
// would probably seriously break method combination if we
// had it.
object[Role.roleKeyName].unshift(new Role(method, i))
}
}
}
Method.setRankHierarchyPosition = (method, index, hierarchyPosition) => {
method._rank[index] = hierarchyPosition
}
Method.clearRank = method => {
method._rank = []
}
Method.isFullySpecified = method => {
for (var i = 0; i < method.minimalSelector; i++) {
if (!method._rank.hasOwnProperty(i)) {
return false
}
}
return true
}
Method.score = method => {
// TODO - this makes all items in the list equal
return method._rank.reduce((a, b) => a + b, 0)
}
genfun-4.0.1/lib/role.js 0000664 0000000 0000000 00000000626 13075001565 0015051 0 ustar 00root root 0000000 0000000 'use strict'
/*
* Role
*
* A Role encapsulates a particular object's 'role' in a method's
* dispatch. They are added directly to the selector for a method, and thus
* do not prevent the objects a method was defined on from being garbage
* collected.
*/
module.exports = Role
function Role (method, position) {
this.method = method
this.position = position
}
Role.roleKeyName = Symbol('roles')
genfun-4.0.1/lib/util.js 0000664 0000000 0000000 00000002041 13075001565 0015056 0 ustar 00root root 0000000 0000000 'use strict'
module.exports.isObjectProto = isObjectProto
function isObjectProto (obj) {
return obj === Object.prototype
}
const _null = {}
const _undefined = {}
const Bool = Boolean
const Num = Number
const Str = String
const boolCache = {
true: new Bool(true),
false: new Bool(false)
}
const numCache = {}
const strCache = {}
/*
* Returns a useful dispatch object for value using a process similar to
* the ToObject operation specified in http://es5.github.com/#x9.9
*/
module.exports.dispatchableObject = dispatchableObject
function dispatchableObject (value) {
// To shut up jshint, which doesn't let me turn off this warning.
const Obj = Object
if (value === null) { return _null }
if (value === undefined) { return _undefined }
switch (typeof value) {
case 'object': return value
case 'boolean': return boolCache[value]
case 'number': return numCache[value] || (numCache[value] = new Num(value))
case 'string': return strCache[value] || (strCache[value] = new Str(value))
default: return new Obj(value)
}
}
genfun-4.0.1/package.json 0000664 0000000 0000000 00000002472 13075001565 0015273 0 ustar 00root root 0000000 0000000 {
"name": "genfun",
"description": "Fast, prototype-friendly multimethods.",
"homepage": "http://github.com/zkat/genfun",
"keywords": [
"clos",
"functional",
"oop",
"util",
"object oriented",
"prototypes",
"multimethod",
"generic functions",
"multiple dispatch",
"polymorphism",
"polymorphic",
"protocols"
],
"author": "Kat Marchรกn ",
"repository": {
"type": "git",
"url": "git://github.com/zkat/genfun"
},
"main": "lib/genfun.js",
"version": "4.0.1",
"license": "CC0-1.0",
"files": [
"lib/*.js"
],
"devDependencies": {
"mocha": "^3.2.0",
"nyc": "^10.2.0",
"standard": "^10.0.2",
"standard-version": "^4.0.0",
"weallbehave": "^1.0.3",
"weallcontribute": "^1.0.8"
},
"readmeFilename": "README.md",
"scripts": {
"prerelease": "npm t",
"postrelease": "npm publish && git push --follow-tags",
"pretest": "standard lib",
"release": "standard-version -s",
"test": "nyc -- mocha --reporter spec",
"update-coc": "weallbehave -o . && git add CODE_OF_CONDUCT.md && git commit -m 'docs(coc): updated CODE_OF_CONDUCT.md'",
"update-contrib": "weallcontribute -o . && git add CONTRIBUTING.md && git commit -m 'docs(contributing): updated CONTRIBUTING.md'"
},
"dependencies": {}
}
genfun-4.0.1/test/ 0000775 0000000 0000000 00000000000 13075001565 0013757 5 ustar 00root root 0000000 0000000 genfun-4.0.1/test/genfun.js 0000664 0000000 0000000 00000035500 13075001565 0015602 0 ustar 00root root 0000000 0000000 /* global describe, it */
'use strict'
var assert = require('assert')
var genfun = require('..')
describe('genfun', function () {
describe('genfun()', function () {
it('creates a new genfun', function () {
assert.equal('function', typeof genfun())
})
it('calls noApplicableMethod if called without adding methods', function () {
var frob = genfun()
assert.throws(
function () { frob() },
/No applicable method found/,
'noApplicableMethod message when called without methods')
genfun.noApplicableMethod.add([frob], function () {
return 'success'
})
assert.equal(frob(), 'success')
})
})
describe('noApplicableMethod', function () {
var frob = genfun()
var container = { frob: frob }
var data = [1, 2, 3]
it('throws an exception if there is no applicable method', function () {
assert.throws(frob, function (err) { return err instanceof Error })
})
it('includes the types of the inputs in the message', function () {
assert.throws(function () { frob(data) }, function (err) {
return err.message === 'No applicable method found when called ' +
'with arguments of types: (Array)'
})
assert.throws(function () { frob({}) }, function (err) {
return err.message === 'No applicable method found when called ' +
'with arguments of types: (Object)'
})
})
it('includes the original call arguments in the Error instance', function () {
assert.throws(function () { frob(data) }, function (err) {
return err.args.length === 1 && err.args[0] === data
})
})
it('includes the `this` argument in the Error instance', function () {
assert.throws(function () { frob.call(data) }, function (err) {
return err.thisArg === data
})
})
it('can be modified so something different happens if dispatch fails', function () {
genfun.noApplicableMethod.add([frob], function () {
return arguments
})
var result = container.frob('foo')
assert.equal(frob, result[0])
assert.equal(container, result[1])
assert.equal('foo', result[2][0])
})
it('is only called when dispatch fails', function () {
frob.add([], function () {
return 'regular method'
})
assert.equal('regular method', frob())
})
})
describe('#apply', function () {
describe('basic call semantics', function () {
var frob = genfun()
frob.add([], function () {
return {'this': this, 'arguments': arguments}
})
var container = {frob: frob}
it('can be called like a normal function', function () {
assert.equal('success', frob('success')['arguments'][0])
assert.equal(container, container.frob()['this'])
})
it('can be called using .call', function () {
assert.equal('success', frob.call(null, 'success')['arguments'][0])
assert.equal(container, frob.call(container)['this'])
})
it('can be called using .apply', function () {
assert.equal('success', frob.apply(null, ['success'])['arguments'][0])
assert.equal(container, frob.apply(container)['this'])
})
it('calls noApplicableMethod if there are no methods defined')
})
describe('nextMethod', function () {
it('allows the next applicable method to be called', function () {
var frob = genfun()
var obj = Object.create({})
var objChild = Object.create(obj)
frob.add([Object], function () {
return 'default'
})
frob.add([obj], function (o, nextMethod) {
return nextMethod()
})
frob.add([objChild], function (o, nextMethod) {
return nextMethod()
})
assert.equal('default', frob(obj))
assert.equal('default', frob(objChild))
})
it('can only be called when there is a next method available', function () {
var frob = genfun()
var obj = Object.create({})
frob.add([frob], function (o, next) {
return next()
})
assert.throws(function () { frob(Object.create(obj)) })
frob.add([Object], function () { return 'ok!' })
assert.equal('ok!', frob(Object.create(obj)))
})
it('calls the next method using the original arguments', function () {
var frob = genfun()
var obj = {}
frob.add([Object], function () {
return {
args: arguments,
thisval: this
}
})
frob.add([obj], function (o, nextMethod) {
return nextMethod()
})
var ret = frob.call('test', obj)
assert.equal(obj, ret.args[0])
assert.equal('test', ret.thisval)
})
it('accepts new arguments for the next method to use', function () {
var frob = genfun()
var obj = {name: 'whoosh'}
frob.add([Object], function (arg) {
return arg + ' called next.'
})
frob.add([obj], function (x, nextMethod) {
return 'And so then, ' + nextMethod(obj.name)
})
assert.equal('And so then, whoosh called next.', frob(obj))
})
it('allows rebinding of `this` in the next method')
})
describe('hasNextMethod', function () {
it('returns true if there is a next method available')
it('can only be called in the scope of a method')
})
describe('noNextMethod', function () {
it('throws an error by default')
it('can have methods defined on it to replace the behavior per-genfun')
})
describe('method combination', function () {
})
describe('dispatch', function () {
describe('basic single dispatch', function () {
var frob = genfun()
var container = {frob: frob}
var Ctr = function () {}
frob.add([Ctr], function (ctr) {
return {
arguments: arguments,
this: this
}
})
it('dispatches methods based on the prototype of its argument', function () {
var obj = new Ctr()
assert.equal(obj, frob(obj).arguments[0])
})
it('fails if there is no method defined for the given argument', function () {
assert.throws(function () { return frob('nothing') })
})
it('properly binds `this` in the method to the genfun\'s `this`', function () {
assert.equal(container, container.frob(new Ctr()).this)
})
it('dispatches the most specific method when multiple methods apply', function () {
frob.add([Object], function (obj) {
return 'NOPE'
})
var obj = new Ctr()
assert.equal(obj, frob(obj).arguments[0])
})
it('can dispatch on objects where [[Proto]] is null', function () {
var frob = genfun()
var nullProto = Object.create(null)
frob.add([nullProto], function () {
return 'nullProto'
})
assert.equal('nullProto', frob(nullProto))
})
it('calls noApplicableMethod correctly if [[Proto]] is null and no applicable method exists for the argument', function () {
var frob = genfun()
var nullProto = Object.create(null)
frob.add([Object], function () {
return 'whatever'
})
genfun.noApplicableMethod.add([frob], function () {
return 'nullProto'
})
assert.equal('nullProto', frob(nullProto))
})
it('handles `null` definitions and dispatch', function () {
var frob = genfun()
frob.add([null], function () { return 'ok' })
assert.equal(frob(null), 'ok', 'dispatched on null')
assert.throws(function () {
frob(undefined)
}, /no applicable method/i)
})
it('handles `undefined` definitions and dispatch', function () {
var frob = genfun()
frob.add([undefined], function () { return 'ok' })
assert.equal(frob(undefined), 'ok', 'dispatched on undefined')
assert.throws(function () {
frob(null)
}, /no applicable method/i)
})
})
describe('ToObject dispatch conversion', function () {
it('dispatches primitives based on equality', function () {
var frob = genfun()
frob.add([true], function () { return 'bool' })
frob.add([1], function () { return 'number' })
frob.add(['hej'], function () { return 'str' })
assert.equal(frob(true), 'bool', 'yay bool')
assert.equal(frob(1), 'number', 'yay number')
assert.equal(frob('hej'), 'str', 'yay str')
assert.throws(function () {
frob(false)
}, /no applicable method/i)
assert.throws(function () {
frob(2)
}, /no applicable method/i)
assert.throws(function () {
frob('bai')
}, /no applicable method/i)
})
it('passes original primitive into the method function', function () {
var frob = genfun()
frob.add(['foo'], function (str) { return str })
assert.equal(frob('foo'), 'foo', 'got the same thing back')
assert.equal(typeof frob('foo'), 'string', 'it is a string')
})
})
describe('Object.prototype empty-index shorthand', function () {
var frob = genfun()
it('lets you write empty array indices into dispatch array to mean Object.prototype', function () {
frob.add([,Number], function (x, num) {
return x
})
frob.add([String, Number], function (x, num) {
return num
})
frob.add([], function () {
return 'nomethod'
})
assert.equal(5, frob(5, 10))
assert.equal(10, frob('5', 10))
assert.equal('nomethod', frob(Object.create(null), 5))
})
})
describe('0-arity dispatch', function () {
var frob = genfun()
frob.add([], function (arg) { return arg })
it('dispatches to a single method when only one method with an empty dispatch array is defined', function () {
var val = {}
assert.equal(val, frob(val))
assert.equal(undefined, frob())
})
it('dispatches to the empty/default method when an arg\'s [[Proto]] is null')
})
describe('multi-argument dispatch', function () {
it('compares all given arguments to the dispatch lists for its methods')
it('weighs methods based on the arguments\' distance to dispatch prototypes')
it('gives greater weight to earlier arguments')
it('fails dispatch when an object with null [[Proto]] with no applicable roles is involved', function () {
var frob = genfun()
var nullProto = Object.create(null)
frob.add([Object, Object], function () {
return 'please no'
})
genfun.noApplicableMethod.add([frob], function () {
return 'success'
})
assert.equal('please no', frob({}, {}))
assert.equal('success', frob(nullProto, {}))
assert.equal('success', frob({}, nullProto))
assert.equal('success', frob(nullProto, nullProto))
})
})
describe('variable arity dispatch', function () {
it('treats \'unfilled\' spaces like Object.prototype when comparing ' +
'methods with dispatch arrays of different lengths')
it('handles complex interactions between all the dispatch features', function () {
var frobnicate = genfun()
frobnicate.add([Number], function (num) {
return 'one number: ' + num
})
frobnicate.add([String], function (str) {
return 'one string: ' + str
})
frobnicate.add([String, Number], function (string, number) {
return 'string + number: ' + string + ', ' + number
})
frobnicate.add([Number, String], function (number, string) {
return 'number + string: ' + number + ', ' + string
})
frobnicate.add([], function () {
return 'Dispatch fell through'
})
frobnicate.add([Number, , String], function (number, anything, string) {
return 'number + anything + string: '
+ number + ', ' + anything + ', ' + string
})
function test (expected, args) {
assert.equal(expected, frobnicate.apply(null, args))
}
test('string + number: foo, 1', [new String('foo'), new Number(1)])
test('number + string: 1, foo', [1, 'foo'])
test('one number: 1', [1, 2])
test('one number: 1', [1])
test('one string: str', ['str'])
test('Dispatch fell through', [true])
test('Dispatch fell through', [])
test('number + anything + string: 1, true, foo', [1, true, 'foo'])
})
})
it('treats empty array items (`[x, ,z]`) like Object.prototype', function () {
var frob = genfun()
var x = {}
frob.add([x, ,x], function (a, b, c) {
return '3-arg method'
})
frob.add([], function () {
return '0-arg method'
})
assert.equal('3-arg method', frob(x, x, x))
assert.equal('3-arg method', frob(x, {}, x))
assert.equal('0-arg method', frob(x, Object.create(null), x))
})
})
})
describe('Genfun#add', function () {
it('defines a new method on the genfun')
it('is accessible as a method on genfuns', function () {
var frob = genfun()
frob.add([String], function (str) { return str + '!' })
assert.equal('success!', frob('success'))
})
it('can define methods that dispatch on objects with null [[Proto]]', function () {
var frob = genfun()
var nullProto = Object.create(null)
frob.add([nullProto, nullProto], function () {
return 'success'
})
assert.equal('success', frob(nullProto, nullProto))
})
it('defines and returns a noApplicableMethod method if given an empty array', function () {
var frob = genfun()
frob.add([String], function () { return 'nop' })
frob.add([], function () { return 'yup' })
assert.equal('yup', frob(Object.create(null)))
})
it('errors if any of the arguments given are primitives')
})
describe('Genfun#hasMethod', function () {
it('returns true if there are applicable methods', function () {
var parent = {}
var child = Object.create(parent)
var frob = genfun().add([parent], function () {
throw new Error('should not be called')
})
assert.ok(frob.hasMethod(parent))
assert.ok(frob.hasMethod(child))
assert.ok(frob.hasMethod(child, 'huh'))
assert.ok(!frob.hasMethod({}))
})
})
describe('removeMethod', function () {
it('undefines a previously defined method on the genfun')
it('can remove methods that dispatch on objects with null [[Proto]]')
})
})