From e2f748e63d621045ddd56832ef3fcd97ed26d61b Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Fri, 27 Mar 2015 15:51:06 +0100 Subject: [PATCH 001/103] Initial commit --- packages/xo-collection/.gitignore | 28 ++ packages/xo-collection/LICENSE | 662 ++++++++++++++++++++++++++++++ packages/xo-collection/README.md | 2 + 3 files changed, 692 insertions(+) create mode 100644 packages/xo-collection/.gitignore create mode 100644 packages/xo-collection/LICENSE create mode 100644 packages/xo-collection/README.md diff --git a/packages/xo-collection/.gitignore b/packages/xo-collection/.gitignore new file mode 100644 index 000000000..59d842baa --- /dev/null +++ b/packages/xo-collection/.gitignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript diff --git a/packages/xo-collection/LICENSE b/packages/xo-collection/LICENSE new file mode 100644 index 000000000..cebe0354b --- /dev/null +++ b/packages/xo-collection/LICENSE @@ -0,0 +1,662 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md new file mode 100644 index 000000000..abef15571 --- /dev/null +++ b/packages/xo-collection/README.md @@ -0,0 +1,2 @@ +# collection +A collection class with a batch feature with commit/rollback/replay From c3a01c240b0133a9f4d857379cb9c8578c5fc904 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Fri, 27 Mar 2015 10:32:20 +0100 Subject: [PATCH 002/103] First base --- packages/xo-collection/.jshintrc | 93 +++++++++++ packages/xo-collection/collection.js | 238 +++++++++++++++++++++++++++ 2 files changed, 331 insertions(+) create mode 100644 packages/xo-collection/.jshintrc create mode 100644 packages/xo-collection/collection.js diff --git a/packages/xo-collection/.jshintrc b/packages/xo-collection/.jshintrc new file mode 100644 index 000000000..9e30c8a86 --- /dev/null +++ b/packages/xo-collection/.jshintrc @@ -0,0 +1,93 @@ +{ + // Julien Fontanet JSHint configuration + // https://gist.github.com/julien-f/8095615 + // + // Changes from defaults: + // - all enforcing options (except `++` & `--`) enabled + // - single quotes + // - indentation set to 2 instead of 4 + // - almost all relaxing options disabled + // - environments are set to Node.js + // + // See http://jshint.com/docs/ for more details + + "maxerr" : 50, // {int} Maximum error before stopping + + // Enforcing + "bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase" : true, // true: Identifiers must be in camelCase + "curly" : true, // true: Require {} for every new block or scope + "eqeqeq" : true, // true: Require triple equals (===) for comparison + "forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty() + "freeze" : true, // true: Prohibit overwriting prototypes of native objects (Array, Date, ...) + "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "indent" : 2, // {int} Number of spaces to use for indentation + "latedef" : true, // true: Require variables/functions to be defined before being used + "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty" : true, // true: Prohibit use of empty blocks + "nonbsp" : true, // true: Prohibit use of non breakable spaces + "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus" : false, // true: Prohibit use of `++` & `--` + "quotmark" : "single", // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) + "unused" : true, // true: Require all defined variables be used + "strict" : false, // true: Requires all functions run in ES5 Strict Mode + "maxcomplexity" : 7, // {int} Max cyclomatic complexity per function + "maxdepth" : 3, // {int} Max depth of nested blocks (within functions) + "maxlen" : 80, // {int} Max number of characters per line + "maxparams" : 4, // {int} Max number of formal params allowed per function + "maxstatements" : 20, // {int} Max number statements per function + + // Relaxing + "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss" : false, // true: Tolerate assignments where comparisons would be expected + "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // true: Tolerate use of `== null` + "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`) + "evil" : false, // true: Tolerate use of `eval` and `new Function()` + "expr" : false, // true: Tolerate `ExpressionStatement` as Programs + "funcscope" : false, // true: Tolerate defining variables inside control statements + "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') + "iterator" : false, // true: Tolerate using the `__iterator__` property + "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak" : false, // true: Tolerate possibly unsafe line breakings + "laxcomma" : false, // true: Tolerate comma-first style coding + "loopfunc" : false, // true: Tolerate functions being defined in loops + "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "multistr" : false, // true: Tolerate multi-line strings + "notypeof" : false, // true: Tolerate typeof comparison with unknown values. + "proto" : false, // true: Tolerate using the `__proto__` property + "scripturl" : false, // true: Tolerate script-targeted URLs + "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` + "validthis" : false, // true: Tolerate using this in a non-constructor function + "noyield" : false, // true: Tolerate generators without yields + + // Environments + "browser" : false, // Web Browser (window, document, etc) + "browserify" : false, // Browserify (node.js code in the browser) + "couch" : false, // CouchDB + "devel" : false, // Development/debugging (alert, confirm, etc) + "dojo" : false, // Dojo Toolkit + "jquery" : false, // jQuery + "mocha" : false, // mocha + "mootools" : false, // MooTools + "node" : true, // Node.js + "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) + "phantom" : false, // PhantomJS + "prototypejs" : false, // Prototype and Scriptaculous + "rhino" : false, // Rhino + "worker" : false, // Web Workers + "wsh" : false, // Windows Scripting Host + "yui" : false, // Yahoo User Interface + + // Custom Globals + "globals" : {} // additional predefined global variables +} diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js new file mode 100644 index 000000000..c236b3c71 --- /dev/null +++ b/packages/xo-collection/collection.js @@ -0,0 +1,238 @@ +import makeError from 'make-error'; + +var IllegalKey = makeError('IllegalKey'); +var OverrideViolation = makeError('OverrideViolation'); +var NotFound = makeError('NotFound'); +var TransactionAlreadyOpened = makeError('TransactionAlreadyOpened'); +var NoTransactionOpened = makeError('NoTransactionOpened'); + +class Collection { + + constructor(strictMode = true) { + + this._collection = {}; + this._strictMode = strictMode; + this._transaction = null; + + } + + begin(callback = undefined) { + + try { + + if (this._strictMode && null !== this._transaction) { + throw new TransactionAlreadyOpened('A transaction is already opened'); + } + + this._transaction = this._transaction || []; + + if ('function' === typeof callback) { + callback(null, this); + } else { + return this; + } + + + } catch (err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + commit(callback = undefined) { + + try { + + if (this._strictMode && null === this._transaction) { + throw new NoTransactionOpened('No opened transaction to commit.'); + } + + let transactionLog = this._transaction || []; + this._transaction = null; + + if ('function' === typeof callback) { + callback(null, transactionLog); + } else { + return transactionLog; + } + + + } catch (err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + insert(id, item, callback = undefined) { + + try { + + id = this.checkId(id); + + if (this._strictMode && this._has(id)) { + throw new OverrideViolation( + 'An insertion must not override the pre-existing key ' + id + '. ' + + 'Consider using update instead depending on your use case.' + ); + } + + this._collection[id] = item; + + if ('function' === typeof callback) { + callback(null, this); + } else { + return this; + } + + } catch (err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + update(id, item, callback = undefined) { + + try { + + id = this.checkId(id); + + if (this._strictMode && !this._has(id)) { + throw new NotFound( + 'No item to update at this key ' + id + '. ' + + 'Consider using insert instead depending on your usecase.' + ); + } + + this._collection[id] = item; + + if ('function' === typeof callback) { + callback(null, this); + } else { + return this; + } + + } catch (err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + delete(id, callback = undefined) { + + try { + + id = this.checkId(id); + + if (this._strictMode && !this._has(id)) { + throw new NotFound( + 'No item to remove at key' + id + '.' + ); + } + + delete this._collection[id]; + + if ('function' === typeof callback) { + callback(null, this); + } else { + return this; + } + + } catch (err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + get(id, callback = undefined) { + + try { + + id = this.checkId(id); + + if (this._strictMode && !this._has(id)) { + throw new NotFound( + 'No item found at key ' + id + ); + } + + if ('function' === typeof callback) { + callback(null, this._collection[id]); + } else { + return this._collection[id]; + } + + } catch (err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + checkId (id) { + + if (undefined === id || null === id) { + throw new IllegalKey('Illegal key : ' + id); + } + + id = this._strictMode && id || String(id); + if ('string' === typeof id && id.length > 0) { + return id; + } else { + throw new IllegalKey('Key must be a non-empty string'); + } + + } + + has(id) { + + return this._has(this.checkId(id)); + + } + + _has(id) { + + return this._collection.hasOwnProperty(id); + + } + +} + +export var Collection = Collection; +export var IllegalKey = IllegalKey; +export var OverrideViolation = OverrideViolation; +export var NotFound = NotFound; \ No newline at end of file From cdb9c661bdf1ad282f78dcccf65b5f823f404cb9 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Fri, 27 Mar 2015 15:33:21 +0100 Subject: [PATCH 003/103] A first version without unit tests, but a gross test script --- packages/xo-collection/collection.js | 298 ++++++++++++++++++++++++--- packages/xo-collection/package.json | 15 ++ packages/xo-collection/test.js | 65 ++++++ 3 files changed, 346 insertions(+), 32 deletions(-) create mode 100644 packages/xo-collection/package.json create mode 100644 packages/xo-collection/test.js diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index c236b3c71..d056cbb58 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -1,17 +1,21 @@ import makeError from 'make-error'; -var IllegalKey = makeError('IllegalKey'); +var IllegalId = makeError('IllegalId'); var OverrideViolation = makeError('OverrideViolation'); var NotFound = makeError('NotFound'); var TransactionAlreadyOpened = makeError('TransactionAlreadyOpened'); var NoTransactionOpened = makeError('NoTransactionOpened'); +var FailedRollback = makeError('FailedRollback'); +var FailedReplay = makeError('FailedReplay'); +var UnrecognizedTransactionItem = makeError('UnrecognizedTransactionItem'); +var UnexpectedLogFormat = makeError('UnexpectedLogFormat'); +var UnexpectedLogItemData = makeError('UnexpectedLogItemData'); class Collection { - constructor(strictMode = true) { + constructor() { this._collection = {}; - this._strictMode = strictMode; this._transaction = null; } @@ -20,11 +24,11 @@ class Collection { try { - if (this._strictMode && null !== this._transaction) { + if (null !== this._transaction) { throw new TransactionAlreadyOpened('A transaction is already opened'); } - this._transaction = this._transaction || []; + this._transaction = []; if ('function' === typeof callback) { callback(null, this); @@ -49,11 +53,11 @@ class Collection { try { - if (this._strictMode && null === this._transaction) { + if (null === this._transaction) { throw new NoTransactionOpened('No opened transaction to commit.'); } - let transactionLog = this._transaction || []; + let transactionLog = this._transaction; this._transaction = null; if ('function' === typeof callback) { @@ -75,20 +79,226 @@ class Collection { } + rollback(callback = undefined) { + + try { + + if (null === this._transaction) { + throw new NoTransactionOpened('No opened transaction to rollback.'); + } + + let log = this._transaction; + this._transaction = null; + + return this._rollback(log, callback); + + } catch(err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + _rollback(log, callback = undefined) { + + try { + + if (!Array.isArray(log)) { + throw new UnexpectedLogFormat('A transaction log must be an Array.'); + } + + let item; + let done = []; + + while(item = log.pop()) { + try { + + this.checkLogItem(item); + + switch (item.action) { + case 'insert': + this.delete(item.id); + break; + case 'update': + this.update(item.id, item.former); + break; + case 'delete': + this.insert(item.id, item.former); + break; + default: + throw new UnrecognizedTransactionItem( + 'Unrecognized item action : "' + item.action + + '" at index ' + log.lenght + '.' + ); + } + + done.unshift(item); + } catch(err) { + let exc = new FailedRollback( + 'Rollback failed on index ' + log.lenght + '.' + ); + exc.undone = log; + exc.done = done; + exc.internal = err; + exc.failedAction = item; + exc.index = log.lenght; + throw exc; + } + } + + if ('function' === typeof callback) { + callback(null, this); + } else { + return this; + } + + } catch(err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + replay(log, callback = undefined) { + + try { + + if (!Array.isArray(log)) { + throw new UnexpectedLogFormat('A transaction log must be an Array.'); + } + + let item; + let done = []; + + while(item = log.shift()) { + try { + + this.checkLogItem(item); + + switch (item.action) { + case 'insert': + this.insert(item.id, item.item); + break; + case 'update': + this.update(item.id, item.item); + break; + case 'delete': + this.delete(item.id); + break; + default: + throw new UnrecognizedTransactionItem( + 'Unrecognized item action : "' + item.action + + '" at index ' + done.lenght + '.' + ); + } + + done.push(item); + } catch(err) { + let exc = new FailedReplay( + 'Replay failed on index ' + done.lenght + '.' + ); + exc.undone = log; + exc.done = done; + exc.internal = err; + exc.failedAction = item; + exc.index = done.lenght; + throw exc; + } + } + + if ('function' === typeof callback) { + callback(null, this); + } else { + return this; + } + + } catch(err) { + + if ('function' === typeof callback) { + callback(err); + } else { + throw err; + } + + } + + } + + checkLogItem (item) { + + if (!item.hasOwnProperty('id')) { + throw new UnexpectedLogItemData( + 'Missing id for ' + item.action + ' object.' + ); + } + + let checkFormer = () => { + if (!item.hasOwnProperty('former')) { + throw new UnexpectedLogItemData( + 'Missing former item in ' + item.action + ' object.' + ); + } + }; + + let checkItem = () => { + if (!item.hasOwnProperty('item')) { + throw new UnexpectedLogItemData( + 'Missing item in ' + item.action + ' object.' + ); + } + }; + + switch (item.action) { + + case 'update': + checkItem(); + case 'delete': + checkFormer(); + break; + case 'insert': + checkItem(); + break; + + default: + throw new UnrecognizedTransactionItem( + 'Unrecognizes item action : "' + item.action + '.' + ); + } + + } + insert(id, item, callback = undefined) { try { - id = this.checkId(id); + this.checkId(id); - if (this._strictMode && this._has(id)) { + if (this._has(id)) { throw new OverrideViolation( - 'An insertion must not override the pre-existing key ' + id + '. ' + + 'An insertion must not override the pre-existing id ' + id + '. ' + 'Consider using update instead depending on your use case.' ); } this._collection[id] = item; + + if (this._transaction) { + this._transaction.push({ + action: 'insert', + id, + item + }); + } if ('function' === typeof callback) { callback(null, this); @@ -112,16 +322,28 @@ class Collection { try { - id = this.checkId(id); + this.checkId(id); - if (this._strictMode && !this._has(id)) { + if (!this._has(id)) { throw new NotFound( - 'No item to update at this key ' + id + '. ' + + 'No item to update at id ' + id + '. ' + 'Consider using insert instead depending on your usecase.' ); } + + let former = this._collection[id]; + this._collection[id] = item; + + if (this._transaction) { + this._transaction.push({ + action: 'update', + id, + former, + item + }); + } if ('function' === typeof callback) { callback(null, this); @@ -145,15 +367,25 @@ class Collection { try { - id = this.checkId(id); + this.checkId(id); - if (this._strictMode && !this._has(id)) { + if (!this._has(id)) { throw new NotFound( - 'No item to remove at key' + id + '.' + 'No item to remove at id' + id + '.' ); } + let former = this._collection[id]; + delete this._collection[id]; + + if (this._transaction) { + this._transaction.push({ + action:'delete', + id, + former + }); + } if ('function' === typeof callback) { callback(null, this); @@ -177,11 +409,11 @@ class Collection { try { - id = this.checkId(id); + this.checkId(id); - if (this._strictMode && !this._has(id)) { + if (!this._has(id)) { throw new NotFound( - 'No item found at key ' + id + 'No item found at id ' + id ); } @@ -205,15 +437,8 @@ class Collection { checkId (id) { - if (undefined === id || null === id) { - throw new IllegalKey('Illegal key : ' + id); - } - - id = this._strictMode && id || String(id); - if ('string' === typeof id && id.length > 0) { - return id; - } else { - throw new IllegalKey('Key must be a non-empty string'); + if ('string' !== typeof id || id.length < 1) { + throw new IllegalId('id must be a non-empty string'); } } @@ -232,7 +457,16 @@ class Collection { } -export var Collection = Collection; -export var IllegalKey = IllegalKey; -export var OverrideViolation = OverrideViolation; -export var NotFound = NotFound; \ No newline at end of file +export default { + Collection, + IllegalId, + OverrideViolation, + NotFound, + TransactionAlreadyOpened, + NoTransactionOpened, + FailedRollback, + FailedReplay, + UnrecognizedTransactionItem, + UnexpectedLogFormat, + UnexpectedLogItemData +}; \ No newline at end of file diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json new file mode 100644 index 000000000..f382fd471 --- /dev/null +++ b/packages/xo-collection/package.json @@ -0,0 +1,15 @@ +{ + "name": "xo-collection", + "version": "0.0.0", + "description": "A generice batch collection attempt", + "main": "collection.js", + "dependencies": { + "make-error": "^0.3.0" + }, + "devDependencies": {}, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Fabrice Marsaud ", + "license": "aGPLv3" +} diff --git a/packages/xo-collection/test.js b/packages/xo-collection/test.js new file mode 100644 index 000000000..71cf03352 --- /dev/null +++ b/packages/xo-collection/test.js @@ -0,0 +1,65 @@ +import xoCollection from './collection'; + +var co = new xoCollection.Collection(); + +co.begin(); + +co.insert('a', 1000); +console.log('a', co.get('a')); +co.update('a', 2000); +console.log('a', co.get('a')); +co.delete('a'); +try { +console.log(co.get('a')); +} catch(e) { + console.error(e); +} + +console.log(co.commit()); + +console.log('====='); + +co.insert('b', 100); +console.log('b', co.get('b')); +co.begin(); +co.update('b', 200); +console.log('b', co.get('b')); +co.insert('c', 300); +co.update('b', 400); +console.log('b', co.get('b'), 'c', co.get('c')); +co.delete('b'); +try { +console.log(co.get('b')); +} catch(e) { + console.error(e); +} + +co.rollback(); + +console.log('b', co.get('b')); +try { +console.log(co.get('c')); +} catch(e) { + console.error(e); +} + +console.log('====='); + +var coa = new xoCollection.Collection(); +coa.insert('x', 999); +coa.begin(); +coa.insert('a', 100); +coa.update('a', 150); +coa.insert('b', 200); +console.log('a', coa.get('a'), 'b', coa.get('b'), 'x', coa.get('x')); +var log = coa.commit(); +var cob = new xoCollection.Collection(); +cob.replay(log); +console.log('a', cob.get('a'), 'b', cob.get('b')); +try { +console.log(cob.get('x')); +} catch(e) { + console.error(e); +} + +process.exit(0); From 19cd5c8881fce8b6f3f83d99fd90cd8858640ed0 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Fri, 27 Mar 2015 15:52:54 +0100 Subject: [PATCH 004/103] Minor renaming --- packages/xo-collection/test.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/xo-collection/test.js b/packages/xo-collection/test.js index 71cf03352..9d003cdff 100644 --- a/packages/xo-collection/test.js +++ b/packages/xo-collection/test.js @@ -1,6 +1,6 @@ -import xoCollection from './collection'; +import Collection from './collection'; -var co = new xoCollection.Collection(); +var co = new Collection.Collection(); co.begin(); @@ -45,7 +45,7 @@ console.log(co.get('c')); console.log('====='); -var coa = new xoCollection.Collection(); +var coa = new Collection.Collection(); coa.insert('x', 999); coa.begin(); coa.insert('a', 100); @@ -53,7 +53,7 @@ coa.update('a', 150); coa.insert('b', 200); console.log('a', coa.get('a'), 'b', coa.get('b'), 'x', coa.get('x')); var log = coa.commit(); -var cob = new xoCollection.Collection(); +var cob = new Collection.Collection(); cob.replay(log); console.log('a', cob.get('a'), 'b', cob.get('b')); try { From a9ea1a02ed7d1352ddbc8794fe7bb30bec9b91b6 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Fri, 27 Mar 2015 16:43:43 +0100 Subject: [PATCH 005/103] Use let and const --- packages/xo-collection/collection.js | 40 ++++++++++++++-------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index d056cbb58..f2bec2822 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -1,15 +1,15 @@ import makeError from 'make-error'; -var IllegalId = makeError('IllegalId'); -var OverrideViolation = makeError('OverrideViolation'); -var NotFound = makeError('NotFound'); -var TransactionAlreadyOpened = makeError('TransactionAlreadyOpened'); -var NoTransactionOpened = makeError('NoTransactionOpened'); -var FailedRollback = makeError('FailedRollback'); -var FailedReplay = makeError('FailedReplay'); -var UnrecognizedTransactionItem = makeError('UnrecognizedTransactionItem'); -var UnexpectedLogFormat = makeError('UnexpectedLogFormat'); -var UnexpectedLogItemData = makeError('UnexpectedLogItemData'); +const IllegalId = makeError('IllegalId'); +const OverrideViolation = makeError('OverrideViolation'); +const NotFound = makeError('NotFound'); +const TransactionAlreadyOpened = makeError('TransactionAlreadyOpened'); +const NoTransactionOpened = makeError('NoTransactionOpened'); +const FailedRollback = makeError('FailedRollback'); +const FailedReplay = makeError('FailedReplay'); +const UnrecognizedTransactionItem = makeError('UnrecognizedTransactionItem'); +const UnexpectedLogFormat = makeError('UnexpectedLogFormat'); +const UnexpectedLogItemData = makeError('UnexpectedLogItemData'); class Collection { @@ -57,7 +57,7 @@ class Collection { throw new NoTransactionOpened('No opened transaction to commit.'); } - let transactionLog = this._transaction; + const transactionLog = this._transaction; this._transaction = null; if ('function' === typeof callback) { @@ -87,7 +87,7 @@ class Collection { throw new NoTransactionOpened('No opened transaction to rollback.'); } - let log = this._transaction; + const log = this._transaction; this._transaction = null; return this._rollback(log, callback); @@ -113,7 +113,7 @@ class Collection { } let item; - let done = []; + const done = []; while(item = log.pop()) { try { @@ -139,7 +139,7 @@ class Collection { done.unshift(item); } catch(err) { - let exc = new FailedRollback( + const exc = new FailedRollback( 'Rollback failed on index ' + log.lenght + '.' ); exc.undone = log; @@ -178,7 +178,7 @@ class Collection { } let item; - let done = []; + const done = []; while(item = log.shift()) { try { @@ -204,7 +204,7 @@ class Collection { done.push(item); } catch(err) { - let exc = new FailedReplay( + const exc = new FailedReplay( 'Replay failed on index ' + done.lenght + '.' ); exc.undone = log; @@ -242,7 +242,7 @@ class Collection { ); } - let checkFormer = () => { + const checkFormer = () => { if (!item.hasOwnProperty('former')) { throw new UnexpectedLogItemData( 'Missing former item in ' + item.action + ' object.' @@ -250,7 +250,7 @@ class Collection { } }; - let checkItem = () => { + const checkItem = () => { if (!item.hasOwnProperty('item')) { throw new UnexpectedLogItemData( 'Missing item in ' + item.action + ' object.' @@ -332,7 +332,7 @@ class Collection { } - let former = this._collection[id]; + const former = this._collection[id]; this._collection[id] = item; @@ -375,7 +375,7 @@ class Collection { ); } - let former = this._collection[id]; + const former = this._collection[id]; delete this._collection[id]; From 48d9fde3b6ea47995f1ca59ffd2a0a70b91eea0a Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Mon, 30 Mar 2015 09:31:42 +0200 Subject: [PATCH 006/103] Left over solution --- packages/xo-collection/collection.js | 53 +++++++++++++++++++++------- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index f2bec2822..f33ad4f4e 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -10,6 +10,8 @@ const FailedReplay = makeError('FailedReplay'); const UnrecognizedTransactionItem = makeError('UnrecognizedTransactionItem'); const UnexpectedLogFormat = makeError('UnexpectedLogFormat'); const UnexpectedLogItemData = makeError('UnexpectedLogItemData'); +const AlreadyPaused = makeError('AlreadyPaused'); +const NothingToFlush = makeError('NothingToFlush'); class Collection { @@ -17,6 +19,31 @@ class Collection { this._collection = {}; this._transaction = null; + this._track = []; + this._pause = false; + + } + + pause() { + + if (this._pause) { + throw new AlreadyPaused('Already paused'); + } + this._pause = true; + + } + + flush(callback = undefined) { + + if (!this._pause) { + throw new NothingToFlush('NothingToFlush'); + } + + this._pause = false; + let track = this._track; + this._track = []; + + return this.replay(track, callback); } @@ -290,10 +317,11 @@ class Collection { ); } - this._collection[id] = item; - - if (this._transaction) { - this._transaction.push({ + if (!this._pause) { + this._collection[id] = item; + } + else { + this._track.push({ action: 'insert', id, item @@ -331,13 +359,12 @@ class Collection { ); } - const former = this._collection[id]; - this._collection[id] = item; - - if (this._transaction) { - this._transaction.push({ + if (!this._pause) { + this._collection[id] = item; + } else { + this._track.push({ action: 'update', id, former, @@ -377,10 +404,10 @@ class Collection { const former = this._collection[id]; - delete this._collection[id]; - - if (this._transaction) { - this._transaction.push({ + if (!this._pause) { + delete this._collection[id]; + } else { + this._track.push({ action:'delete', id, former From 265d77d776eb4658e55d26407ad79719d1c685a4 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Tue, 31 Mar 2015 16:09:05 +0200 Subject: [PATCH 007/103] First main methods. No events, no buffer yet --- packages/xo-collection/collection.js | 552 +++++----------------- packages/xo-collection/collection.spec.js | 241 ++++++++++ packages/xo-collection/package.json | 10 +- packages/xo-collection/test.js | 104 ++-- 4 files changed, 433 insertions(+), 474 deletions(-) create mode 100644 packages/xo-collection/collection.spec.js diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index f33ad4f4e..bf87933d8 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -1,499 +1,195 @@ import makeError from 'make-error'; -const IllegalId = makeError('IllegalId'); -const OverrideViolation = makeError('OverrideViolation'); -const NotFound = makeError('NotFound'); -const TransactionAlreadyOpened = makeError('TransactionAlreadyOpened'); -const NoTransactionOpened = makeError('NoTransactionOpened'); -const FailedRollback = makeError('FailedRollback'); -const FailedReplay = makeError('FailedReplay'); -const UnrecognizedTransactionItem = makeError('UnrecognizedTransactionItem'); -const UnexpectedLogFormat = makeError('UnexpectedLogFormat'); -const UnexpectedLogItemData = makeError('UnexpectedLogItemData'); -const AlreadyPaused = makeError('AlreadyPaused'); -const NothingToFlush = makeError('NothingToFlush'); +const AlreadyBuffering = makeError('AlreadyBuffering'); +const NotBuffering = makeError('NotBuffering'); +const IllegalAdd = makeError('IllegalAdd'); +const DuplicateEntry = makeError('DuplicateEntry'); +const NoSuchEntry = makeError('NoSuchEntry'); class Collection { - constructor() { + constructor () { - this._collection = {}; - this._transaction = null; - this._track = []; - this._pause = false; + this._map = {}; + this._buffering = false; + this._size = 0; } - pause() { + _initBuffer () { - if (this._pause) { - throw new AlreadyPaused('Already paused'); + this._buffer = { + remove: [], + add: [], + update: [] + }; + + } + + bufferChanges (state = true) { + + if (state && this._buffer) { + throw new AlreadyBuffering('Already buffering'); // FIXME Really ?... } - this._pause = true; - - } - - flush(callback = undefined) { - - if (!this._pause) { - throw new NothingToFlush('NothingToFlush'); + if (!state && !this._buffer) { + throw new NotBuffering('Not buffering'); // FIXME Really ?... } + this._buffer = state; - this._pause = false; - let track = this._track; - this._track = []; - - return this.replay(track, callback); - - } - - begin(callback = undefined) { - - try { - - if (null !== this._transaction) { - throw new TransactionAlreadyOpened('A transaction is already opened'); - } - - this._transaction = []; - - if ('function' === typeof callback) { - callback(null, this); - } else { - return this; - } - - - } catch (err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } - + if (!this._buffer) { + this._initBuffer(); } } - commit(callback = undefined) { + flush () { - try { + if (!this._buffer) { + throw new NotBuffering('NothingToFlush'); + } - if (null === this._transaction) { - throw new NoTransactionOpened('No opened transaction to commit.'); - } + this._buffering = false; // FIXME Really ? - const transactionLog = this._transaction; - this._transaction = null; + // TODO Throws buffered events - if ('function' === typeof callback) { - callback(null, transactionLog); + this._initBuffer(); + + } + + _touch (key, action) { + + // TODO Buffers changes or throws an event + + } + + _set (key, value) { + + this._map[key] = value; + this._touch(key, 'update'); + return this; + + } + + _unset (key) { + + delete this._map[key]; + this._touch(key, 'remove'); + return this; + } + + getId (item) { + return item.id; + } + + has (key) { + + return this._map.hasOwnProperty(key); + + } + + resolveEntry (keyOrObjectWithId, valueIfKey = null) { + + let value; + let key = (undefined !== keyOrObjectWithId) ? + this.getId(keyOrObjectWithId) : + undefined; + + if (undefined === key) { + if (arguments.length < 2) { + throw new IllegalAdd(); } else { - return transactionLog; + key = keyOrObjectWithId; + value = valueIfKey; } + } else { + value = keyOrObjectWithId; + } + return [key, value]; + } - } catch (err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } + _assertHas(key) { + if (!this.has(key)) { + throw new NoSuchEntry(); } } - rollback(callback = undefined) { - - try { - - if (null === this._transaction) { - throw new NoTransactionOpened('No opened transaction to rollback.'); - } - - const log = this._transaction; - this._transaction = null; - - return this._rollback(log, callback); - - } catch(err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } + _assertNotHas(key) { + if (this.has(key)) { + throw new DuplicateEntry(); } } - _rollback(log, callback = undefined) { + add (keyOrObjectWithId, valueIfKey = null) { - try { + const [key, value] = this.resolveEntry.apply(this, arguments); - if (!Array.isArray(log)) { - throw new UnexpectedLogFormat('A transaction log must be an Array.'); - } + this._assertNotHas(key); + this._size++; - let item; - const done = []; + return this._set(key, value); - while(item = log.pop()) { - try { + } - this.checkLogItem(item); + set (keyOrObjectWithId, valueIfKey = null) { - switch (item.action) { - case 'insert': - this.delete(item.id); - break; - case 'update': - this.update(item.id, item.former); - break; - case 'delete': - this.insert(item.id, item.former); - break; - default: - throw new UnrecognizedTransactionItem( - 'Unrecognized item action : "' + item.action + - '" at index ' + log.lenght + '.' - ); - } - - done.unshift(item); - } catch(err) { - const exc = new FailedRollback( - 'Rollback failed on index ' + log.lenght + '.' - ); - exc.undone = log; - exc.done = done; - exc.internal = err; - exc.failedAction = item; - exc.index = log.lenght; - throw exc; - } - } - - if ('function' === typeof callback) { - callback(null, this); - } else { - return this; - } - - } catch(err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } + const [key, value] = this.resolveEntry.apply(this, arguments); + if (!this.has(key)) { + this._size++; } - } - - replay(log, callback = undefined) { - - try { - - if (!Array.isArray(log)) { - throw new UnexpectedLogFormat('A transaction log must be an Array.'); - } - - let item; - const done = []; - - while(item = log.shift()) { - try { - - this.checkLogItem(item); - - switch (item.action) { - case 'insert': - this.insert(item.id, item.item); - break; - case 'update': - this.update(item.id, item.item); - break; - case 'delete': - this.delete(item.id); - break; - default: - throw new UnrecognizedTransactionItem( - 'Unrecognized item action : "' + item.action + - '" at index ' + done.lenght + '.' - ); - } - - done.push(item); - } catch(err) { - const exc = new FailedReplay( - 'Replay failed on index ' + done.lenght + '.' - ); - exc.undone = log; - exc.done = done; - exc.internal = err; - exc.failedAction = item; - exc.index = done.lenght; - throw exc; - } - } - - if ('function' === typeof callback) { - callback(null, this); - } else { - return this; - } - - } catch(err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } - - } + return this._set(key, value); } - checkLogItem (item) { + get (key) { - if (!item.hasOwnProperty('id')) { - throw new UnexpectedLogItemData( - 'Missing id for ' + item.action + ' object.' - ); - } + this._assertHas(key); - const checkFormer = () => { - if (!item.hasOwnProperty('former')) { - throw new UnexpectedLogItemData( - 'Missing former item in ' + item.action + ' object.' - ); - } - }; + return this._map[key]; + } - const checkItem = () => { - if (!item.hasOwnProperty('item')) { - throw new UnexpectedLogItemData( - 'Missing item in ' + item.action + ' object.' - ); - } - }; + update (keyOrObjectWithId, valueIfKey = null) { - switch (item.action) { + const [key, value] = this.resolveEntry.apply(this, arguments); - case 'update': - checkItem(); - case 'delete': - checkFormer(); - break; - case 'insert': - checkItem(); - break; + this._assertHas(key); - default: - throw new UnrecognizedTransactionItem( - 'Unrecognizes item action : "' + item.action + '.' - ); - } + return this._set(key, value); } - insert(id, item, callback = undefined) { + remove (keyOrObjectWithId) { - try { + const [key] = this.resolveEntry(keyOrObjectWithId, null); - this.checkId(id); + this._assertHas(key); + this._size--; - if (this._has(id)) { - throw new OverrideViolation( - 'An insertion must not override the pre-existing id ' + id + '. ' + - 'Consider using update instead depending on your use case.' - ); - } - - if (!this._pause) { - this._collection[id] = item; - } - else { - this._track.push({ - action: 'insert', - id, - item - }); - } - - if ('function' === typeof callback) { - callback(null, this); - } else { - return this; - } - - } catch (err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } - - } + return this._unset(key); } - update(id, item, callback = undefined) { - - try { - - this.checkId(id); - - if (!this._has(id)) { - throw new NotFound( - 'No item to update at id ' + id + '. ' + - 'Consider using insert instead depending on your usecase.' - ); - } - - const former = this._collection[id]; - - if (!this._pause) { - this._collection[id] = item; - } else { - this._track.push({ - action: 'update', - id, - former, - item - }); - } - - if ('function' === typeof callback) { - callback(null, this); - } else { - return this; - } - - } catch (err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } - - } - + get size () { + return this._size; } - delete(id, callback = undefined) { - - try { - - this.checkId(id); - - if (!this._has(id)) { - throw new NotFound( - 'No item to remove at id' + id + '.' - ); - } - - const former = this._collection[id]; - - if (!this._pause) { - delete this._collection[id]; - } else { - this._track.push({ - action:'delete', - id, - former - }); - } - - if ('function' === typeof callback) { - callback(null, this); - } else { - return this; - } - - } catch (err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } - - } - - } - - get(id, callback = undefined) { - - try { - - this.checkId(id); - - if (!this._has(id)) { - throw new NotFound( - 'No item found at id ' + id - ); - } - - if ('function' === typeof callback) { - callback(null, this._collection[id]); - } else { - return this._collection[id]; - } - - } catch (err) { - - if ('function' === typeof callback) { - callback(err); - } else { - throw err; - } - - } - - } - - checkId (id) { - - if ('string' !== typeof id || id.length < 1) { - throw new IllegalId('id must be a non-empty string'); - } - - } - - has(id) { - - return this._has(this.checkId(id)); - - } - - _has(id) { - - return this._collection.hasOwnProperty(id); - + get all () { + return this._map; } } export default { Collection, - IllegalId, - OverrideViolation, - NotFound, - TransactionAlreadyOpened, - NoTransactionOpened, - FailedRollback, - FailedReplay, - UnrecognizedTransactionItem, - UnexpectedLogFormat, - UnexpectedLogItemData + AlreadyBuffering, + NotBuffering, + IllegalAdd, + DuplicateEntry, + NoSuchEntry }; \ No newline at end of file diff --git a/packages/xo-collection/collection.spec.js b/packages/xo-collection/collection.spec.js new file mode 100644 index 000000000..fa00aa2e0 --- /dev/null +++ b/packages/xo-collection/collection.spec.js @@ -0,0 +1,241 @@ +var chai = require('chai'); +var expect = chai.expect; +var dirtyChai = require('dirty-chai'); +chai.use(dirtyChai); +var leche = require('leche'); + +console.log(expect); + +var Collection = require('./collection'); + +var col = new Collection.Collection(); + +describe('collection', function () { + + // ============================================================ + + var fixtureValues1 = { + 'primitive value': ['foo1', 1], + 'array value': ['bar1', [1,2]], + 'object value': ['baz1', {a:1, b:2}] + }; + + describe('add', function () { + + leche.withData(fixtureValues1, function (key, value) { + + it('Adds a new entry to the collection', function () { + expect(col.add(key, value)).to.eql(col); + }); + + }); + + leche.withData(fixtureValues1, function (key, value) { + + it('We cannot add on a pre-existing key', function () { + expect(function () { + col.add(key, value); + }).to.throw(Collection.DuplicateEntry); + }); + + }); + + }); + + // ============================================================ + + var fixtureValues2 = { + 'primitive value': ['foo2', 1], + 'array value': ['bar2', [1,2]], + 'object value': ['baz2', {a:1, b:2}] + }; + + describe('set', function () { + + leche.withData(fixtureValues2, function (key, value) { + + it('Sets an entry of the collection...', function () { + expect(col.set(key, value)).to.eql(col); + }); + + }); + + leche.withData(fixtureValues2, function (key, value) { + + it('...would it already exists or not', function () { + expect(col.set(key, value)).to.eql(col); + }); + + }); + + }); + + // ============================================================ + + var fixtureUnexisting = { + 'Unexisting key/entry': ['wat', 'any'] + }; + + describe('get', function () { + + leche.withData(fixtureValues1, function (key, value) { + + it('Returns the value of an entry of the collection...', function () { + expect(col.get(key)).to.eql(value); + }); + + }); + + leche.withData(fixtureValues2, function (key, value) { + + it('Returns the value of an entry of the collection...', function () { + expect(col.get(key)).to.eql(value); + }); + + }); + + leche.withData(fixtureUnexisting, function (key) { + + it('...or throws if it does not exist', function () { + expect(function () { + col.get(key); + }).to.throw(Collection.NoSuchEntry); + }); + + }); + + }); + + // ============================================================ + + var fixtureUpdates = { + 'primitive value': ['foo2', 3], + 'array value': ['bar2', [3,4]], + 'object value': ['baz2', {c:3, d:4}] + }; + + describe('update', function () { + + leche.withData(fixtureUpdates, function (key, value) { + + it('updates the given entries...', function () { + expect(col.update(key, value)).to.eql(col); + }); + + }); + + leche.withData(fixtureUpdates, function (key, value) { + + it('...so we can see the values we get have changed accordingly', function () { + expect(col.get(key)).to.eql(value); + }); + + }); + + leche.withData(fixtureUnexisting, function (key, value) { + + it('If the entry does not exist, updating throws', function () { + expect(function () { + col.update(key, value); + }).to.throw(Collection.NoSuchEntry); + }); + + }); + + }); + + // ============================================================ + + describe('remove', function () { + + leche.withData(fixtureValues2, function (key) { + + it('removes the given entries...', function () { + expect(col.remove(key)).to.eql(col); + }); + + }); + + leche.withData(fixtureValues2, function (key) { + + it('...so trying to get them again throws...', function () { + expect(function () { + col.get(key); + }).to.throw(Collection.NoSuchEntry); + }); + + }); + + leche.withData(fixtureValues2, function (key) { + + it('...and trying to remove them again also throws', function () { + expect(function () { + col.remove(key); + }).to.throw(Collection.NoSuchEntry); + }); + + }); + + }); + + // ============================================================ + + describe('has', function () { + + leche.withData(fixtureValues1, function (key) { + + it('Tells us if an entry exists...', function () { + expect(col.has(key)).to.be.true(); + }); + + }); + + leche.withData(fixtureValues2, function (key) { + + it('...or not', function () { + expect(col.has(key)).to.be.false(); + }); + + }); + + }); + + // ============================================================ + + describe('size', function () { + + it('Reveals the number of existing entries', function () { + expect(col.size).to.eq(Object.keys(fixtureValues1).length); + }); + + }); + + // ============================================================ + + describe('all', function () { + + leche.withData(fixtureValues1, function (key, value) { + + it('Gives access to the internal collection...', function () { + expect(col.all).to.have.ownProperty(key); + expect(col.all[key]).to.eq(value); + }); + + }); + + leche.withData(fixtureValues2, function (key) { + + it('Gives access to the internal collection...', function () { + expect(col.all).to.not.have.ownProperty(key); + expect(col.all[key]).to.eq(undefined); + }); + + }); + + it('Gives access to the internal collection...', function () { + expect(col.size).to.eq(Object.keys(col.all).length); + }); + + }); + +}); \ No newline at end of file diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index f382fd471..fcf939331 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -6,9 +6,15 @@ "dependencies": { "make-error": "^0.3.0" }, - "devDependencies": {}, + "devDependencies": { + "babel": "^4.7.16", + "chai": "^2.2.0", + "dirty-chai": "^1.2.0", + "leche": "^2.1.1", + "mocha": "^2.2.1" + }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "mocha --require babel/register *.spec.js" }, "author": "Fabrice Marsaud ", "license": "aGPLv3" diff --git a/packages/xo-collection/test.js b/packages/xo-collection/test.js index 9d003cdff..2ac59da7f 100644 --- a/packages/xo-collection/test.js +++ b/packages/xo-collection/test.js @@ -1,65 +1,81 @@ import Collection from './collection'; -var co = new Collection.Collection(); +let col = new Collection.Collection(); -co.begin(); +col.add('foo', 1); + +// An object with id property + +// ==================== +// Jouer sur le passage par référence, et la convention d'objets avec une prop ID + +let obj = {id: 'bar', content: 2}; +col.add(obj); +console.log(obj.get('bar')); +// > {id: 'bar', content: 2} + +col.bufferChanges(true); +col.update('bar').content = 4; +// update accesses obj at bar key and marks bar as updated. No event emitted. + +col.get('bar').content = 5; +obj.content = 6; +// bar is already marked as updated, so ... + +col.flush(); +// ...Emits an update as bar has been "updated to 6" + +col.bufferChanges(true); +col.update(obj).content = 7; // Short writing without knowing ID +// WARNING, do not change ID after adding ... + +col.bufferChanges(false); +col.flush(); +// No event emitted ... exception thrown ?... +col.bufferChanges(true); +col.update(obj); +col.flush(); +// Emits an update event as bar has been "updated to 7" + +// ------------------------------------------------------------ +// Special cases : +let foo = {id: 'foo'}; +let bar = {id: 'bar'}; +col.add(foo); -co.insert('a', 1000); -console.log('a', co.get('a')); -co.update('a', 2000); -console.log('a', co.get('a')); -co.delete('a'); try { -console.log(co.get('a')); + col.update(foo, bar); } catch(e) { + // Throws an instant exception on ID violation console.error(e); } -console.log(co.commit()); - -console.log('====='); - -co.insert('b', 100); -console.log('b', co.get('b')); -co.begin(); -co.update('b', 200); -console.log('b', co.get('b')); -co.insert('c', 300); -co.update('b', 400); -console.log('b', co.get('b'), 'c', co.get('c')); -co.delete('b'); try { -console.log(co.get('b')); + col.udpate('foo', bar); } catch(e) { + // Same console.error(e); } -co.rollback(); - -console.log('b', co.get('b')); try { -console.log(co.get('c')); -} catch(e) { + col.update(foo).id = 'bar'; +} catch (e) { + // Throws an exception at Event emission (key !== content.id) console.error(e); } -console.log('====='); +col.bufferChanges(true); +col.remove(foo); +col.add(foo); +col.bufferChanges(false); +// Silent...(No events) -var coa = new Collection.Collection(); -coa.insert('x', 999); -coa.begin(); -coa.insert('a', 100); -coa.update('a', 150); -coa.insert('b', 200); -console.log('a', coa.get('a'), 'b', coa.get('b'), 'x', coa.get('x')); -var log = coa.commit(); -var cob = new Collection.Collection(); -cob.replay(log); -console.log('a', cob.get('a'), 'b', cob.get('b')); +col.bufferChanges(true); +col.update(foo).id = 'bar'; +// Nothing happens try { -console.log(cob.get('x')); -} catch(e) { - console.error(e); + col.flush(); +} catch (e) { + // Throws + console.log(e); } - -process.exit(0); From 92d7d6192633c74f95e9aafd1e025141ea73332d Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Tue, 31 Mar 2015 17:08:41 +0200 Subject: [PATCH 008/103] Various fixes and enhancements --- packages/xo-collection/collection.js | 52 +++++++++++++++------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index bf87933d8..6c6786893 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -26,39 +26,33 @@ class Collection { } - bufferChanges (state = true) { + bufferChanges () { - if (state && this._buffer) { + if (this._buffer) { throw new AlreadyBuffering('Already buffering'); // FIXME Really ?... } - if (!state && !this._buffer) { - throw new NotBuffering('Not buffering'); // FIXME Really ?... - } - this._buffer = state; - if (!this._buffer) { + this._buffer = true; + + return () => { + + if (!this._buffer) { + throw new NotBuffering('Nothing to flush'); // FIXME Really ? + } + + this._buffering = false; // FIXME Really ? + + // TODO Emits events for buffered changes + this._initBuffer(); - } - } - - flush () { - - if (!this._buffer) { - throw new NotBuffering('NothingToFlush'); - } - - this._buffering = false; // FIXME Really ? - - // TODO Throws buffered events - - this._initBuffer(); + }; } _touch (key, action) { - // TODO Buffers changes or throws an event + // TODO Buffers changes or emits an event } @@ -75,15 +69,18 @@ class Collection { delete this._map[key]; this._touch(key, 'remove'); return this; + } getId (item) { + return item.id; + } has (key) { - return this._map.hasOwnProperty(key); + return Object.hasOwnProperty.call(this._map, key); } @@ -106,6 +103,7 @@ class Collection { } return [key, value]; + } _assertHas(key) { @@ -116,7 +114,7 @@ class Collection { } - _assertNotHas(key) { + _assertHasNot(key) { if (this.has(key)) { throw new DuplicateEntry(); @@ -128,7 +126,7 @@ class Collection { const [key, value] = this.resolveEntry.apply(this, arguments); - this._assertNotHas(key); + this._assertHasNot(key); this._size++; return this._set(key, value); @@ -176,11 +174,15 @@ class Collection { } get size () { + return this._size; + } get all () { + return this._map; + } } From a3d7e541d3f79c2af2c880503b4a42e140dd7f31 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Wed, 1 Apr 2015 15:06:39 +0200 Subject: [PATCH 009/103] Events implemented and tested, without buffering --- .../xo-collection/collection.event.spec.js | 210 ++++++++++++++++++ packages/xo-collection/collection.js | 73 +++--- packages/xo-collection/collection.spec.js | 75 ++++--- packages/xo-collection/package.json | 4 +- 4 files changed, 300 insertions(+), 62 deletions(-) create mode 100644 packages/xo-collection/collection.event.spec.js diff --git a/packages/xo-collection/collection.event.spec.js b/packages/xo-collection/collection.event.spec.js new file mode 100644 index 000000000..dc4759533 --- /dev/null +++ b/packages/xo-collection/collection.event.spec.js @@ -0,0 +1,210 @@ +var chai = require('chai'); +var expect = chai.expect; +var dirtyChai = require('dirty-chai'); +chai.use(dirtyChai); +var leche = require('leche'); +var sinon = require('sinon'); + +var Collection = require('./collection'); + +var col = new Collection.Collection(); + +describe('collection events', function () { + + // ============================================================ + + var data1 = { + 'primitive value': ['foo1', 1], + 'array value': ['bar1', [1,2]], + 'object value': ['baz1', {a:1, b:2}] + }; + + var addSpy; + var updateSpy; + var removeSpy; + + beforeEach(function () { + + addSpy = sinon.spy(); + updateSpy = sinon.spy(); + removeSpy = sinon.spy(); + col.on('add', addSpy); + col.on('update', updateSpy); + col.on('remove', removeSpy); + + }); + + afterEach(function () { + + col.removeAllListeners(); + + }); + + // Collection is empty ======================================================= + + describe('add', function () { + + leche.withData(data1, function (key, value) { + + it('Emits an add event transporting the key and value', function () { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.add(key, value)).to.eql(col); + expect(addSpy.called).to.be.true(); + expect(addSpy.calledWith({key: value})).to.be.true(); + + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + }); + + }); + + }); + + var updateData1 = { + 'primitive value': ['foo1', 3], + 'array value': ['bar1', [3,4]], + 'object value': ['baz1', {c:2, d:4}] + }; + + // Collection contains data1 ================================================= + + describe('update', function () { + + leche.withData(updateData1, function (key, value) { + + it('Emits an update event transporting the key and value', function () { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.update(key, value)).to.eql(col); + expect(updateSpy.called).to.be.true(); + expect(updateSpy.calledWith({key: value})).to.be.true(); + + expect(addSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + }); + + }); + + }); + + var data2 = { + 'primitive value': ['foo2', 1], + 'array value': ['bar2', [1,2]], + 'object value': ['baz2', {a:1, b:2}] + }; + + // Collection contains data1 updated ========================================= + + describe('set', function () { + + leche.withData(data1, function (key, value) { + + it('Emits an update event for pre-existing keys', function () { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.update(key, value)).to.eql(col); + expect(updateSpy.called).to.be.true(); + expect(updateSpy.calledWith({key: value})).to.be.true(); + + expect(addSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + }); + + }); + + // Collection contains data1 ============================================= + + leche.withData(data2, function (key, value) { + + it('Emits an add event for unexisting keys', function () { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.add(key, value)).to.eql(col); + expect(addSpy.called).to.be.true(); + expect(addSpy.calledWith({key: value})).to.be.true(); + + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + }); + + }); + + }); + + // Collection contains data1 & data 2 ======================================== + + describe('remove', function () { + + leche.withData(data1, function (key, value) { + + it('Emits an remove event transporting the key and removed value', function () { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.remove(key)).to.eql(col); + expect(removeSpy.called).to.be.true(); + expect(removeSpy.calledWith({key: value})).to.be.true(); + + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + }); + + }); + + }); + + // Collection contains data 2 ================================================ + + describe('clear', function () { + + var clearedData; + + it('Emits a remove event', function() { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.clear()).to.eq(col); + expect(removeSpy.calledOnce).to.be.true(); + + clearedData = removeSpy.lastCall.args[0]; + + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + }); + + it('Emits no event if collection is empty', function() { + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + + expect(col.clear()).to.eq(col); + + expect(addSpy.called).to.be.false(); + expect(updateSpy.called).to.be.false(); + expect(removeSpy.called).to.be.false(); + }); + + leche.withData(data2, function (key, value) { + + it('Emits a remove event with all cleared data', function () { + + expect(clearedData[key]).to.eq(value); + + }); + + }); + + }); + +}); \ No newline at end of file diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index 6c6786893..2c8f14d19 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -1,4 +1,6 @@ import makeError from 'make-error'; +import events from 'events'; +import _forEach from 'lodash.foreach'; const AlreadyBuffering = makeError('AlreadyBuffering'); const NotBuffering = makeError('NotBuffering'); @@ -6,10 +8,12 @@ const IllegalAdd = makeError('IllegalAdd'); const DuplicateEntry = makeError('DuplicateEntry'); const NoSuchEntry = makeError('NoSuchEntry'); -class Collection { +class Collection extends events.EventEmitter { constructor () { + super(); + this._map = {}; this._buffering = false; this._size = 0; @@ -18,11 +22,7 @@ class Collection { _initBuffer () { - this._buffer = { - remove: [], - add: [], - update: [] - }; + this._buffer = {}; } @@ -50,25 +50,11 @@ class Collection { } - _touch (key, action) { + _touch (action, key, value) { - // TODO Buffers changes or emits an event + // TODO enable buffering - } - - _set (key, value) { - - this._map[key] = value; - this._touch(key, 'update'); - return this; - - } - - _unset (key) { - - delete this._map[key]; - this._touch(key, 'remove'); - return this; + this.emit(action, {key: value}); } @@ -127,9 +113,13 @@ class Collection { const [key, value] = this.resolveEntry.apply(this, arguments); this._assertHasNot(key); - this._size++; - return this._set(key, value); + this._map[key] = value; + + this._size++; + this._touch('add', key, value); + + return this; } @@ -137,11 +127,15 @@ class Collection { const [key, value] = this.resolveEntry.apply(this, arguments); - if (!this.has(key)) { + const action = this.has(key) ? 'update' : 'add'; + this._map[key] = value; + if ('add' === action) { this._size++; } - return this._set(key, value); + this._touch(action, key, value); + + return this; } @@ -158,7 +152,10 @@ class Collection { this._assertHas(key); - return this._set(key, value); + this._map[key] = value; + this._touch('update', key, value); + + return this; } @@ -167,9 +164,27 @@ class Collection { const [key] = this.resolveEntry(keyOrObjectWithId, null); this._assertHas(key); + + const oldValue = this.get(key); + delete this._map[key]; this._size--; - return this._unset(key); + this._touch('remove', key, oldValue); + + return this; + + } + + clear () { + + if (this._size > 0) { + this.emit('remove', this._map); + } + + this._map = {}; + this._size = 0; + + return this; } diff --git a/packages/xo-collection/collection.spec.js b/packages/xo-collection/collection.spec.js index fa00aa2e0..f682b2291 100644 --- a/packages/xo-collection/collection.spec.js +++ b/packages/xo-collection/collection.spec.js @@ -4,17 +4,15 @@ var dirtyChai = require('dirty-chai'); chai.use(dirtyChai); var leche = require('leche'); -console.log(expect); - var Collection = require('./collection'); var col = new Collection.Collection(); describe('collection', function () { - // ============================================================ + // Collection is empty ======================================================= - var fixtureValues1 = { + var data1 = { 'primitive value': ['foo1', 1], 'array value': ['bar1', [1,2]], 'object value': ['baz1', {a:1, b:2}] @@ -22,7 +20,7 @@ describe('collection', function () { describe('add', function () { - leche.withData(fixtureValues1, function (key, value) { + leche.withData(data1, function (key, value) { it('Adds a new entry to the collection', function () { expect(col.add(key, value)).to.eql(col); @@ -30,7 +28,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues1, function (key, value) { + leche.withData(data1, function (key, value) { it('We cannot add on a pre-existing key', function () { expect(function () { @@ -42,9 +40,9 @@ describe('collection', function () { }); - // ============================================================ + // Collection contains data 1 ================================================ - var fixtureValues2 = { + var data2 = { 'primitive value': ['foo2', 1], 'array value': ['bar2', [1,2]], 'object value': ['baz2', {a:1, b:2}] @@ -52,7 +50,7 @@ describe('collection', function () { describe('set', function () { - leche.withData(fixtureValues2, function (key, value) { + leche.withData(data2, function (key, value) { it('Sets an entry of the collection...', function () { expect(col.set(key, value)).to.eql(col); @@ -60,7 +58,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues2, function (key, value) { + leche.withData(data2, function (key, value) { it('...would it already exists or not', function () { expect(col.set(key, value)).to.eql(col); @@ -70,15 +68,15 @@ describe('collection', function () { }); - // ============================================================ + // Collection contains data 1 & 2 ============================================ - var fixtureUnexisting = { + var unexistingData = { 'Unexisting key/entry': ['wat', 'any'] }; describe('get', function () { - leche.withData(fixtureValues1, function (key, value) { + leche.withData(data1, function (key, value) { it('Returns the value of an entry of the collection...', function () { expect(col.get(key)).to.eql(value); @@ -86,7 +84,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues2, function (key, value) { + leche.withData(data2, function (key, value) { it('Returns the value of an entry of the collection...', function () { expect(col.get(key)).to.eql(value); @@ -94,7 +92,7 @@ describe('collection', function () { }); - leche.withData(fixtureUnexisting, function (key) { + leche.withData(unexistingData, function (key) { it('...or throws if it does not exist', function () { expect(function () { @@ -106,9 +104,9 @@ describe('collection', function () { }); - // ============================================================ + // Collection contains data 1 & 2 ============================================ - var fixtureUpdates = { + var updateData2 = { 'primitive value': ['foo2', 3], 'array value': ['bar2', [3,4]], 'object value': ['baz2', {c:3, d:4}] @@ -116,7 +114,7 @@ describe('collection', function () { describe('update', function () { - leche.withData(fixtureUpdates, function (key, value) { + leche.withData(updateData2, function (key, value) { it('updates the given entries...', function () { expect(col.update(key, value)).to.eql(col); @@ -124,7 +122,7 @@ describe('collection', function () { }); - leche.withData(fixtureUpdates, function (key, value) { + leche.withData(updateData2, function (key, value) { it('...so we can see the values we get have changed accordingly', function () { expect(col.get(key)).to.eql(value); @@ -132,7 +130,7 @@ describe('collection', function () { }); - leche.withData(fixtureUnexisting, function (key, value) { + leche.withData(unexistingData, function (key, value) { it('If the entry does not exist, updating throws', function () { expect(function () { @@ -144,11 +142,11 @@ describe('collection', function () { }); - // ============================================================ + // Collection contains data 1 & 2 updated ==================================== describe('remove', function () { - leche.withData(fixtureValues2, function (key) { + leche.withData(data2, function (key) { it('removes the given entries...', function () { expect(col.remove(key)).to.eql(col); @@ -156,7 +154,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues2, function (key) { + leche.withData(data2, function (key) { it('...so trying to get them again throws...', function () { expect(function () { @@ -166,7 +164,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues2, function (key) { + leche.withData(data2, function (key) { it('...and trying to remove them again also throws', function () { expect(function () { @@ -178,11 +176,11 @@ describe('collection', function () { }); - // ============================================================ + // Collection contains data 1 ================================================ describe('has', function () { - leche.withData(fixtureValues1, function (key) { + leche.withData(data1, function (key) { it('Tells us if an entry exists...', function () { expect(col.has(key)).to.be.true(); @@ -190,7 +188,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues2, function (key) { + leche.withData(data2, function (key) { it('...or not', function () { expect(col.has(key)).to.be.false(); @@ -200,21 +198,21 @@ describe('collection', function () { }); - // ============================================================ + // Collection contains data 1 ================================================ describe('size', function () { it('Reveals the number of existing entries', function () { - expect(col.size).to.eq(Object.keys(fixtureValues1).length); + expect(col.size).to.eq(Object.keys(data1).length); }); }); - // ============================================================ + // Collection contains data 1 ================================================ describe('all', function () { - leche.withData(fixtureValues1, function (key, value) { + leche.withData(data1, function (key, value) { it('Gives access to the internal collection...', function () { expect(col.all).to.have.ownProperty(key); @@ -223,7 +221,7 @@ describe('collection', function () { }); - leche.withData(fixtureValues2, function (key) { + leche.withData(data2, function (key) { it('Gives access to the internal collection...', function () { expect(col.all).to.not.have.ownProperty(key); @@ -238,4 +236,17 @@ describe('collection', function () { }); + // Collection contains data 1 ================================================ + + describe('clear', function () { + + it('wipes out all the collection', function () { + expect(col.clear()).to.eq(col); + + expect(col.size).to.eq(0); + expect(col.all).to.eql({}); + }); + + }); + }); \ No newline at end of file diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index fcf939331..22a0312ab 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -4,6 +4,7 @@ "description": "A generice batch collection attempt", "main": "collection.js", "dependencies": { + "lodash.foreach": "^3.0.2", "make-error": "^0.3.0" }, "devDependencies": { @@ -11,7 +12,8 @@ "chai": "^2.2.0", "dirty-chai": "^1.2.0", "leche": "^2.1.1", - "mocha": "^2.2.1" + "mocha": "^2.2.1", + "sinon": "^1.14.1" }, "scripts": { "test": "mocha --require babel/register *.spec.js" From 96ea70c02788c980466151144732904479eb4d79 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Wed, 1 Apr 2015 18:06:23 +0200 Subject: [PATCH 010/103] Buffer implemented and tested --- .../xo-collection/collection.buffer.spec.js | 331 ++++++++++++++++++ packages/xo-collection/collection.js | 68 +++- 2 files changed, 385 insertions(+), 14 deletions(-) create mode 100644 packages/xo-collection/collection.buffer.spec.js diff --git a/packages/xo-collection/collection.buffer.spec.js b/packages/xo-collection/collection.buffer.spec.js new file mode 100644 index 000000000..76cd2344d --- /dev/null +++ b/packages/xo-collection/collection.buffer.spec.js @@ -0,0 +1,331 @@ +var chai = require('chai'); +var expect = chai.expect; +var dirtyChai = require('dirty-chai'); +chai.use(dirtyChai); +var leche = require('leche'); +var sinon = require('sinon'); + +var Collection = require('./collection'); + +describe('collection buffer', function () { + + // ============================================================ + + var col; + + var addSpy, addCount; + var updateSpy, updateCount; + var removeSpy, removeCount; + var flush; + + before(function () { + + col = new Collection.Collection(); + + addSpy = sinon.spy(); + addCount = 0; + updateSpy = sinon.spy(); + updateCount = 0; + removeSpy = sinon.spy(); + removeCount = 0; + + }); + + after(function () { + + col.removeAllListeners(); + + }); + + beforeEach(/*'force flush', */function () { + + col.removeAllListeners(); // flush may emit events + + try { // In case test cases interrupt before flushing + if (flush) { + flush(); + } + } catch(e) { + if (!e instanceof Collection.NotBuffering) { + throw e; + } + } + + col.on('add', addSpy); + col.on('update', updateSpy); + col.on('remove', removeSpy); + + }); + + // Collection is empty ======================================================= + + var data1 = { + foo: 1, + bar: [1, 2], + baz: {a:1, b:2} + }; + + describe('add', function () { + + + it('Emits no event when buffered, all data is emitted when flushed', function () { + + flush = col.bufferChanges(); + + expect(addSpy.callCount).to.eq(addCount); + + for (var prop in data1) { + expect(col.add(prop, data1[prop])).to.eq(col); + } + + expect(addSpy.callCount).to.eq(addCount); + + flush(); + addCount++; + + expect(addSpy.callCount).to.eq(addCount); + expect(addSpy.calledWith(data1)).to.be.true(); + + expect(flush).to.throw(Collection.NotBuffering); + + }); + + }); + + var data2 = { + foo: 3, + bar: [3, 4], + baz: {c:3, d:4} + }; + + var removedKeysData2 = { + foo: null, + bar: null, + baz: null + }; + + describe('update', function () { + + + it('Emits no event when buffered, all data is emitted when flushed', function () { + + flush = col.bufferChanges(); + + expect(updateSpy.callCount).to.eq(updateCount); + + for (var prop in data2) { + expect(col.update(prop, data2[prop])).to.eq(col); + } + + expect(updateSpy.callCount).to.eq(updateCount); + + flush(); + updateCount++; + + expect(updateSpy.callCount).to.eq(addCount); + expect(updateSpy.calledWith(data2)).to.be.true(); + + expect(flush).to.throw(Collection.NotBuffering); + + }); + + }); + + + + describe('remove', function () { + + + it('Emits no event when buffered, removed keys are emitted when flushed', function () { + + flush = col.bufferChanges(); + + expect(removeSpy.callCount).to.eq(removeCount); + + for (var prop in data2) { + expect(col.remove(prop)).to.eq(col); + } + + expect(removeSpy.callCount).to.eq(removeCount); + + flush(); + removeCount++; + + expect(removeSpy.callCount).to.eq(removeCount); + expect(removeSpy.calledWith(removedKeysData2)).to.be.true(); + + expect(flush).to.throw(Collection.NotBuffering); + + }); + + }); + + describe('buffer', function() { + + beforeEach(/*'Init collection before buffering', */function() { + + col.removeAllListeners(); + + col.clear(); + col.add('exist', 0); + col.add('disappear', 3); + + col.on('add', addSpy); + col.on('update', updateSpy); + col.on('remove', removeSpy); + }); + + leche.withData( + { + + 'add && update => add': [ + [ + {action: 'add', key: 'new', value:1}, + {action: 'update', key: 'new', value:2}, + ], + { + add: 1, + update: 0, + remove: 0 + }, + { + add: {'new': 2} + } + ], + + 'update && update => update': [ + [ + {action: 'update', key: 'exist', value:1}, + {action: 'update', key: 'exist', value:2}, + ], + { + add: 0, + update: 1, + remove: 0 + }, + { + update: {'exist': 2} + } + ], + + 'update && remove => remove': [ + [ + {action: 'update', key: 'exist', value:1}, + {action: 'remove', key: 'exist'}, + ], + { + add: 0, + update: 0, + remove: 1 + }, + { + remove: {'exist': null} + } + ], + + 'add && [update &&] remove => nothing': [ + [ + {action: 'add', key: 'new', value:1}, + {action: 'update', key: 'new', value:1}, + {action: 'remove', key: 'new'}, + ], + { + add: 0, + update: 0, + remove: 0 + }, + {} + ], + + 'remove && add => update': [ + [ + {action: 'remove', key: 'exist'}, + {action: 'add', key: 'exist', value:0} + ], + { + add: 0, + update: 1, + remove: 0 + }, + { + update: {'exist': 0} + } + ], + + 'every entry is isolated': [ + [ + {action: 'update', key: 'disappear', value:22}, + {action: 'remove', key: 'disappear'}, + {action: 'add', key: 'new', value:1}, + {action: 'update', key: 'new', value:222}, + {action: 'update', key: 'exist', value:1}, + {action: 'update', key: 'exist', value:2222}, + {action: 'add', key: 'nothing', value:0}, + {action: 'update', key: 'nothing', value:1}, + {action: 'remove', key: 'nothing'}, + + ], + { + add: 1, + update: 1, + remove: 1 + }, + { + remove: {'disappear': null}, + add: {'new': 222}, + update: {'exist': 2222} + } + ] + + + }, + + function (actions, increments, eventArgs) { + + it('Filters side effects forgotten by override', function () { + + expect(addSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); + expect(removeSpy.callCount).to.eq(removeCount); + + flush = col.bufferChanges(); + + actions.forEach(function (action) { + expect( + col[action.action](action.key, action.value) + ).to.eq(col); + }); + + expect(addSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); + expect(removeSpy.callCount).to.eq(removeCount); + + flush(); + expect(flush).to.throw(Collection.NotBuffering); + + addCount += increments.add; + updateCount += increments.update; + removeCount += increments.remove; + + expect(addSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); + expect(removeSpy.callCount).to.eq(removeCount); + + if (eventArgs.add) { + expect(addSpy.calledWith(eventArgs.add)).to.be.true(); + } + if (eventArgs.update) { + expect(updateSpy.calledWith(eventArgs.update)).to.be.true(); + } + if (eventArgs.remove) { + expect(removeSpy.calledWith(eventArgs.remove)).to.be.true(); + } + + }); + + } + ); + + }); + +}); diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index 2c8f14d19..c604d4269 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -20,31 +20,43 @@ class Collection extends events.EventEmitter { } - _initBuffer () { - - this._buffer = {}; - - } - bufferChanges () { - if (this._buffer) { + if (this._buffering) { throw new AlreadyBuffering('Already buffering'); // FIXME Really ?... } - this._buffer = true; + this._buffering = true; + this._buffer = {}; return () => { - if (!this._buffer) { + if (!this._buffering) { throw new NotBuffering('Nothing to flush'); // FIXME Really ? } this._buffering = false; // FIXME Really ? - // TODO Emits events for buffered changes + let data = { + add: {data: {}}, + update: {data: {}}, + remove: {data: {}} + }; - this._initBuffer(); + for (let key in this._buffer) { + data[this._buffer[key]].data[key] = this.has(key) ? + this.get(key) : + null; // 'remove' case + data[this._buffer[key]].has = true; + } + + ['add', 'update', 'remove'].forEach(action => { + if (data[action].has) { + this.emit(action, data[action].data); + } + }); + + delete this._buffer; }; @@ -52,9 +64,36 @@ class Collection extends events.EventEmitter { _touch (action, key, value) { - // TODO enable buffering + if (this._buffering) { - this.emit(action, {key: value}); + switch(action) { + + case 'add': + this._buffer[key] = this._buffer[key] ? 'update' : 'add'; + break; + case 'update': + this._buffer[key] = this._buffer[key] || 'update'; + break; + case 'remove': + switch(this._buffer[key]) { + case undefined: + case 'update': + this._buffer[key] = 'remove'; + break; + case 'add': + delete this._buffer[key]; + break; + + } + break; + } + + + } else { + + this.emit(action, {key: value}); + + } } @@ -169,6 +208,7 @@ class Collection extends events.EventEmitter { delete this._map[key]; this._size--; + // FIXME do we "emit" null in place of oldValue to harmonize with flush remove events ? this._touch('remove', key, oldValue); return this; @@ -177,7 +217,7 @@ class Collection extends events.EventEmitter { clear () { - if (this._size > 0) { + if (this._size > 0) { // FIXME Really ? this.emit('remove', this._map); } From 35c64be3d7e5d98853fa13b8d5dd7b6e0a3df21f Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Thu, 2 Apr 2015 10:14:32 +0200 Subject: [PATCH 011/103] All tests for "simple" buffer --- .../xo-collection/collection.buffer.spec.js | 177 +++++++++++++++++- packages/xo-collection/collection.js | 23 ++- 2 files changed, 195 insertions(+), 5 deletions(-) diff --git a/packages/xo-collection/collection.buffer.spec.js b/packages/xo-collection/collection.buffer.spec.js index 76cd2344d..c12390805 100644 --- a/packages/xo-collection/collection.buffer.spec.js +++ b/packages/xo-collection/collection.buffer.spec.js @@ -92,6 +92,8 @@ describe('collection buffer', function () { }); + // Collection contains data 1 ================================================ + var data2 = { foo: 3, bar: [3, 4], @@ -106,7 +108,7 @@ describe('collection buffer', function () { describe('update', function () { - + it('Emits no event when buffered, all data is emitted when flushed', function () { flush = col.bufferChanges(); @@ -122,7 +124,7 @@ describe('collection buffer', function () { flush(); updateCount++; - expect(updateSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); expect(updateSpy.calledWith(data2)).to.be.true(); expect(flush).to.throw(Collection.NotBuffering); @@ -131,6 +133,34 @@ describe('collection buffer', function () { }); + // Collection contains data 2 (update of data 1 keys) ======================== + + describe('touch', function () { + + + it('Marks a key as buffer-updated, and gives the value for object-property modification cases', function () { + + flush = col.bufferChanges(); + + expect(updateSpy.callCount).to.eq(updateCount); + + for (var prop in data2) { + expect(col.touch(prop)).to.eq(data2[prop]); + } + + expect(updateSpy.callCount).to.eq(updateCount); + + flush(); + updateCount++; + + expect(updateSpy.callCount).to.eq(updateCount); + expect(updateSpy.calledWith(data2)).to.be.true(); + + expect(flush).to.throw(Collection.NotBuffering); + + }); + + }); describe('remove', function () { @@ -160,6 +190,110 @@ describe('collection buffer', function () { }); + // Collection is empty ======================================================= + + var dataBefore = { // Will be removed if not re-added (-> udpate) + foo: 1, + bar: 2, + baz: 3 + }; + + // Buffered from now + + var dataToAdd = { // will be out of events if not post-added (-> add) + qux: 4, + hop: 6 + }; + + var dataToUpdate = { + bar: 22, + }; + + var dataToRemove = { + hop: null, + }; + + // All above will be cleared + + var dataToPostAdd = { + baz: 33, + hip: 5 + }; + + // flush + + var expectedRemovedData = { + foo: null, + bar: null, + }; + + var expectedUpdatedData = { + baz: 33 + }; + + var expectedAddedData = { + hip:5 + }; + + describe('clear', function () { + + + it('acts as a multi-remove', function () { + + var prop; + + for (prop in dataBefore) { + expect(col.add(prop, dataBefore[prop])).to.eq(col); + } + + addCount = addSpy.callCount; // Not buffered, events have been emitted + + flush = col.bufferChanges(); + + expect(addSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); + expect(removeSpy.callCount).to.eq(removeCount); + + for (prop in dataToAdd) { + expect(col.add(prop, dataToAdd[prop])).to.eq(col); + } + for (prop in dataToUpdate) { + expect(col.update(prop, dataToUpdate[prop])).to.eq(col); + } + for (prop in dataToRemove) { + expect(col.remove(prop)).to.eq(col); + } + + expect(col.clear()).to.eq(col); + + for (prop in dataToPostAdd) { + expect(col.add(prop, dataToPostAdd[prop])).to.eq(col); + } + + expect(addSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); + expect(removeSpy.callCount).to.eq(removeCount); + + flush(); + + addCount++; + updateCount++; + removeCount++; + + expect(addSpy.callCount).to.eq(addCount); + expect(updateSpy.callCount).to.eq(updateCount); + expect(removeSpy.callCount).to.eq(removeCount); + + expect(addSpy.calledWith(expectedAddedData)).to.be.true(); + expect(updateSpy.calledWith(expectedUpdatedData)).to.be.true(); + expect(removeSpy.calledWith(expectedRemovedData)).to.be.true(); + + expect(flush).to.throw(Collection.NotBuffering); + + }); + + }); + describe('buffer', function() { beforeEach(/*'Init collection before buffering', */function() { @@ -178,9 +312,10 @@ describe('collection buffer', function () { leche.withData( { - 'add && update => add': [ + 'add && update(|set) => add': [ [ {action: 'add', key: 'new', value:1}, + {action: 'set', key: 'new', value:1.5}, {action: 'update', key: 'new', value:2}, ], { @@ -193,9 +328,26 @@ describe('collection buffer', function () { } ], + 'set(1st == add) && update(|set) => add': [ + [ + {action: 'set', key: 'new', value:1}, + {action: 'update', key: 'new', value:1.5}, + {action: 'set', key: 'new', value:2}, + ], + { + add: 1, + update: 0, + remove: 0 + }, + { + add: {'new': 2} + } + ], + 'update && update => update': [ [ {action: 'update', key: 'exist', value:1}, + {action: 'set', key: 'exist', value:1.5}, {action: 'update', key: 'exist', value:2}, ], { @@ -211,6 +363,7 @@ describe('collection buffer', function () { 'update && remove => remove': [ [ {action: 'update', key: 'exist', value:1}, + {action: 'set', key: 'exist', value:1}, {action: 'remove', key: 'exist'}, ], { @@ -226,7 +379,8 @@ describe('collection buffer', function () { 'add && [update &&] remove => nothing': [ [ {action: 'add', key: 'new', value:1}, - {action: 'update', key: 'new', value:1}, + {action: 'update', key: 'new', value:2}, + {action: 'set', key: 'new', value:3}, {action: 'remove', key: 'new'}, ], { @@ -252,6 +406,21 @@ describe('collection buffer', function () { } ], + 'remove && set => update': [ + [ + {action: 'remove', key: 'exist'}, + {action: 'set', key: 'exist', value:0} + ], + { + add: 0, + update: 1, + remove: 0 + }, + { + update: {'exist': 0} + } + ], + 'every entry is isolated': [ [ {action: 'update', key: 'disappear', value:22}, diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index c604d4269..d22981358 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -198,6 +198,21 @@ class Collection extends events.EventEmitter { } + touch (keyOrObjectWithId) { + + const [key] = this.resolveEntry(keyOrObjectWithId, null); + + this._assertHas(key); + + if (!this._buffering) { // FIXME Really ? + // TODO throw something + } + + this._touch('update', key); + return this.get(key); + + } + remove (keyOrObjectWithId) { const [key] = this.resolveEntry(keyOrObjectWithId, null); @@ -218,7 +233,13 @@ class Collection extends events.EventEmitter { clear () { if (this._size > 0) { // FIXME Really ? - this.emit('remove', this._map); + if (!this._buffering) { + this.emit('remove', this._map); + } else { + for (let key in this._map) { + this._touch('remove', key); + } + } } this._map = {}; From cbd93f450e63706af65c7d188d3420841db0e7a9 Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Thu, 2 Apr 2015 15:32:08 +0200 Subject: [PATCH 012/103] Implementation seems ok. Deeper tests to come --- .../xo-collection/collection.async.spec.js | 132 +++++ .../xo-collection/collection.buffer.spec.js | 500 ------------------ .../xo-collection/collection.event.spec.js | 210 -------- packages/xo-collection/collection.js | 468 +++++++--------- packages/xo-collection/collection.spec.js | 252 --------- packages/xo-collection/package.json | 1 + 6 files changed, 329 insertions(+), 1234 deletions(-) create mode 100644 packages/xo-collection/collection.async.spec.js delete mode 100644 packages/xo-collection/collection.buffer.spec.js delete mode 100644 packages/xo-collection/collection.event.spec.js delete mode 100644 packages/xo-collection/collection.spec.js diff --git a/packages/xo-collection/collection.async.spec.js b/packages/xo-collection/collection.async.spec.js new file mode 100644 index 000000000..a94983e60 --- /dev/null +++ b/packages/xo-collection/collection.async.spec.js @@ -0,0 +1,132 @@ +/* eslint-env mocha */ + +import Collection, {DuplicateEntry, NoSuchEntry} from './collection' + +import eventToPromise from 'event-to-promise' +import sinon from 'sinon' + +import chai from 'chai' +const expect = chai.expect +import dirtyChai from 'dirty-chai' +chai.use(dirtyChai) + +describe('Collection', function () { + beforeEach(function (done) { + this.col = new Collection() + this.col.add('bar', 0) + + process.nextTick(done) + }) + + describe('#add()', function () { + it('adds item to the collection', function () { + const spy = sinon.spy() + this.col.on('add', spy) + + this.col.add('foo', true) + + expect(this.col.get('foo')).to.equal(true) + + // No sync events. + sinon.assert.notCalled(spy) + + // Async event. + return eventToPromise(this.col, 'add').then(function (added) { + expect(added).to.have.all.keys('foo') + expect(added.foo).to.equal(true) + }) + }) + + it('throws an exception if the item already exists', function () { + expect(() => this.col.add('bar', true)).to.throw(DuplicateEntry) + }) + }) + + describe('#update()', function () { + it('updates an item of the collection', function () { + const spy = sinon.spy() + this.col.on('update', spy) + + this.col.update('bar', 1) + expect(this.col.get('bar')).to.equal(1) // Will be forgotten by de-duplication + this.col.update('bar', 2) + expect(this.col.get('bar')).to.equal(2) + + // No sync events. + sinon.assert.notCalled(spy) + + // Async event. + return eventToPromise(this.col, 'update').then(function (updated) { + expect(updated).to.have.all.keys('bar') + expect(updated.bar).to.equal(2) + }) + }) + + it('throws an exception if the item does not exist', function () { + expect(() => this.col.update('baz', true)).to.throw(NoSuchEntry) + }) + }) + + describe('#remove()', function () { + it('removes an item of the collection', function () { + const spy = sinon.spy() + this.col.on('remove', spy) + + this.col.update('bar', 1) + expect(this.col.get('bar')).to.equal(1) // Will be forgotten by de-duplication + this.col.remove('bar') + + // No sync events. + sinon.assert.notCalled(spy) + + // Async event. + return eventToPromise(this.col, 'remove').then(function (removed) { + expect(removed).to.have.all.keys('bar') + expect(removed.bar).to.equal(null) + }) + }) + + it('throws an exception if the item does not exist', function () { + expect(() => this.col.remove('baz', true)).to.throw(NoSuchEntry) + }) + }) + + describe('#set()', function () { + it('adds item if collection has not key', function () { + const spy = sinon.spy() + this.col.on('add', spy) + + this.col.set('foo', true) + + expect(this.col.get('foo')).to.equal(true) + + // No sync events. + sinon.assert.notCalled(spy) + + // Async events. + return eventToPromise(this.col, 'add').then(function (added) { + expect(added).to.have.all.keys('foo') + expect(added.foo).to.equal(true) + }) + }) + + it('updates item if collection has key', function () { + const spy = sinon.spy() + this.col.on('udpate', spy) + + this.col.set('bar', 1) + + expect(this.col.get('bar')).to.equal(1) + + // No sync events. + sinon.assert.notCalled(spy) + + // Async events. + return eventToPromise(this.col, 'update').then(function (updated) { + expect(updated).to.have.all.keys('bar') + expect(updated.bar).to.equal(1) + }) + }) + }) + +}) diff --git a/packages/xo-collection/collection.buffer.spec.js b/packages/xo-collection/collection.buffer.spec.js deleted file mode 100644 index c12390805..000000000 --- a/packages/xo-collection/collection.buffer.spec.js +++ /dev/null @@ -1,500 +0,0 @@ -var chai = require('chai'); -var expect = chai.expect; -var dirtyChai = require('dirty-chai'); -chai.use(dirtyChai); -var leche = require('leche'); -var sinon = require('sinon'); - -var Collection = require('./collection'); - -describe('collection buffer', function () { - - // ============================================================ - - var col; - - var addSpy, addCount; - var updateSpy, updateCount; - var removeSpy, removeCount; - var flush; - - before(function () { - - col = new Collection.Collection(); - - addSpy = sinon.spy(); - addCount = 0; - updateSpy = sinon.spy(); - updateCount = 0; - removeSpy = sinon.spy(); - removeCount = 0; - - }); - - after(function () { - - col.removeAllListeners(); - - }); - - beforeEach(/*'force flush', */function () { - - col.removeAllListeners(); // flush may emit events - - try { // In case test cases interrupt before flushing - if (flush) { - flush(); - } - } catch(e) { - if (!e instanceof Collection.NotBuffering) { - throw e; - } - } - - col.on('add', addSpy); - col.on('update', updateSpy); - col.on('remove', removeSpy); - - }); - - // Collection is empty ======================================================= - - var data1 = { - foo: 1, - bar: [1, 2], - baz: {a:1, b:2} - }; - - describe('add', function () { - - - it('Emits no event when buffered, all data is emitted when flushed', function () { - - flush = col.bufferChanges(); - - expect(addSpy.callCount).to.eq(addCount); - - for (var prop in data1) { - expect(col.add(prop, data1[prop])).to.eq(col); - } - - expect(addSpy.callCount).to.eq(addCount); - - flush(); - addCount++; - - expect(addSpy.callCount).to.eq(addCount); - expect(addSpy.calledWith(data1)).to.be.true(); - - expect(flush).to.throw(Collection.NotBuffering); - - }); - - }); - - // Collection contains data 1 ================================================ - - var data2 = { - foo: 3, - bar: [3, 4], - baz: {c:3, d:4} - }; - - var removedKeysData2 = { - foo: null, - bar: null, - baz: null - }; - - describe('update', function () { - - - it('Emits no event when buffered, all data is emitted when flushed', function () { - - flush = col.bufferChanges(); - - expect(updateSpy.callCount).to.eq(updateCount); - - for (var prop in data2) { - expect(col.update(prop, data2[prop])).to.eq(col); - } - - expect(updateSpy.callCount).to.eq(updateCount); - - flush(); - updateCount++; - - expect(updateSpy.callCount).to.eq(updateCount); - expect(updateSpy.calledWith(data2)).to.be.true(); - - expect(flush).to.throw(Collection.NotBuffering); - - }); - - }); - - // Collection contains data 2 (update of data 1 keys) ======================== - - describe('touch', function () { - - - it('Marks a key as buffer-updated, and gives the value for object-property modification cases', function () { - - flush = col.bufferChanges(); - - expect(updateSpy.callCount).to.eq(updateCount); - - for (var prop in data2) { - expect(col.touch(prop)).to.eq(data2[prop]); - } - - expect(updateSpy.callCount).to.eq(updateCount); - - flush(); - updateCount++; - - expect(updateSpy.callCount).to.eq(updateCount); - expect(updateSpy.calledWith(data2)).to.be.true(); - - expect(flush).to.throw(Collection.NotBuffering); - - }); - - }); - - - describe('remove', function () { - - - it('Emits no event when buffered, removed keys are emitted when flushed', function () { - - flush = col.bufferChanges(); - - expect(removeSpy.callCount).to.eq(removeCount); - - for (var prop in data2) { - expect(col.remove(prop)).to.eq(col); - } - - expect(removeSpy.callCount).to.eq(removeCount); - - flush(); - removeCount++; - - expect(removeSpy.callCount).to.eq(removeCount); - expect(removeSpy.calledWith(removedKeysData2)).to.be.true(); - - expect(flush).to.throw(Collection.NotBuffering); - - }); - - }); - - // Collection is empty ======================================================= - - var dataBefore = { // Will be removed if not re-added (-> udpate) - foo: 1, - bar: 2, - baz: 3 - }; - - // Buffered from now - - var dataToAdd = { // will be out of events if not post-added (-> add) - qux: 4, - hop: 6 - }; - - var dataToUpdate = { - bar: 22, - }; - - var dataToRemove = { - hop: null, - }; - - // All above will be cleared - - var dataToPostAdd = { - baz: 33, - hip: 5 - }; - - // flush - - var expectedRemovedData = { - foo: null, - bar: null, - }; - - var expectedUpdatedData = { - baz: 33 - }; - - var expectedAddedData = { - hip:5 - }; - - describe('clear', function () { - - - it('acts as a multi-remove', function () { - - var prop; - - for (prop in dataBefore) { - expect(col.add(prop, dataBefore[prop])).to.eq(col); - } - - addCount = addSpy.callCount; // Not buffered, events have been emitted - - flush = col.bufferChanges(); - - expect(addSpy.callCount).to.eq(addCount); - expect(updateSpy.callCount).to.eq(updateCount); - expect(removeSpy.callCount).to.eq(removeCount); - - for (prop in dataToAdd) { - expect(col.add(prop, dataToAdd[prop])).to.eq(col); - } - for (prop in dataToUpdate) { - expect(col.update(prop, dataToUpdate[prop])).to.eq(col); - } - for (prop in dataToRemove) { - expect(col.remove(prop)).to.eq(col); - } - - expect(col.clear()).to.eq(col); - - for (prop in dataToPostAdd) { - expect(col.add(prop, dataToPostAdd[prop])).to.eq(col); - } - - expect(addSpy.callCount).to.eq(addCount); - expect(updateSpy.callCount).to.eq(updateCount); - expect(removeSpy.callCount).to.eq(removeCount); - - flush(); - - addCount++; - updateCount++; - removeCount++; - - expect(addSpy.callCount).to.eq(addCount); - expect(updateSpy.callCount).to.eq(updateCount); - expect(removeSpy.callCount).to.eq(removeCount); - - expect(addSpy.calledWith(expectedAddedData)).to.be.true(); - expect(updateSpy.calledWith(expectedUpdatedData)).to.be.true(); - expect(removeSpy.calledWith(expectedRemovedData)).to.be.true(); - - expect(flush).to.throw(Collection.NotBuffering); - - }); - - }); - - describe('buffer', function() { - - beforeEach(/*'Init collection before buffering', */function() { - - col.removeAllListeners(); - - col.clear(); - col.add('exist', 0); - col.add('disappear', 3); - - col.on('add', addSpy); - col.on('update', updateSpy); - col.on('remove', removeSpy); - }); - - leche.withData( - { - - 'add && update(|set) => add': [ - [ - {action: 'add', key: 'new', value:1}, - {action: 'set', key: 'new', value:1.5}, - {action: 'update', key: 'new', value:2}, - ], - { - add: 1, - update: 0, - remove: 0 - }, - { - add: {'new': 2} - } - ], - - 'set(1st == add) && update(|set) => add': [ - [ - {action: 'set', key: 'new', value:1}, - {action: 'update', key: 'new', value:1.5}, - {action: 'set', key: 'new', value:2}, - ], - { - add: 1, - update: 0, - remove: 0 - }, - { - add: {'new': 2} - } - ], - - 'update && update => update': [ - [ - {action: 'update', key: 'exist', value:1}, - {action: 'set', key: 'exist', value:1.5}, - {action: 'update', key: 'exist', value:2}, - ], - { - add: 0, - update: 1, - remove: 0 - }, - { - update: {'exist': 2} - } - ], - - 'update && remove => remove': [ - [ - {action: 'update', key: 'exist', value:1}, - {action: 'set', key: 'exist', value:1}, - {action: 'remove', key: 'exist'}, - ], - { - add: 0, - update: 0, - remove: 1 - }, - { - remove: {'exist': null} - } - ], - - 'add && [update &&] remove => nothing': [ - [ - {action: 'add', key: 'new', value:1}, - {action: 'update', key: 'new', value:2}, - {action: 'set', key: 'new', value:3}, - {action: 'remove', key: 'new'}, - ], - { - add: 0, - update: 0, - remove: 0 - }, - {} - ], - - 'remove && add => update': [ - [ - {action: 'remove', key: 'exist'}, - {action: 'add', key: 'exist', value:0} - ], - { - add: 0, - update: 1, - remove: 0 - }, - { - update: {'exist': 0} - } - ], - - 'remove && set => update': [ - [ - {action: 'remove', key: 'exist'}, - {action: 'set', key: 'exist', value:0} - ], - { - add: 0, - update: 1, - remove: 0 - }, - { - update: {'exist': 0} - } - ], - - 'every entry is isolated': [ - [ - {action: 'update', key: 'disappear', value:22}, - {action: 'remove', key: 'disappear'}, - {action: 'add', key: 'new', value:1}, - {action: 'update', key: 'new', value:222}, - {action: 'update', key: 'exist', value:1}, - {action: 'update', key: 'exist', value:2222}, - {action: 'add', key: 'nothing', value:0}, - {action: 'update', key: 'nothing', value:1}, - {action: 'remove', key: 'nothing'}, - - ], - { - add: 1, - update: 1, - remove: 1 - }, - { - remove: {'disappear': null}, - add: {'new': 222}, - update: {'exist': 2222} - } - ] - - - }, - - function (actions, increments, eventArgs) { - - it('Filters side effects forgotten by override', function () { - - expect(addSpy.callCount).to.eq(addCount); - expect(updateSpy.callCount).to.eq(updateCount); - expect(removeSpy.callCount).to.eq(removeCount); - - flush = col.bufferChanges(); - - actions.forEach(function (action) { - expect( - col[action.action](action.key, action.value) - ).to.eq(col); - }); - - expect(addSpy.callCount).to.eq(addCount); - expect(updateSpy.callCount).to.eq(updateCount); - expect(removeSpy.callCount).to.eq(removeCount); - - flush(); - expect(flush).to.throw(Collection.NotBuffering); - - addCount += increments.add; - updateCount += increments.update; - removeCount += increments.remove; - - expect(addSpy.callCount).to.eq(addCount); - expect(updateSpy.callCount).to.eq(updateCount); - expect(removeSpy.callCount).to.eq(removeCount); - - if (eventArgs.add) { - expect(addSpy.calledWith(eventArgs.add)).to.be.true(); - } - if (eventArgs.update) { - expect(updateSpy.calledWith(eventArgs.update)).to.be.true(); - } - if (eventArgs.remove) { - expect(removeSpy.calledWith(eventArgs.remove)).to.be.true(); - } - - }); - - } - ); - - }); - -}); diff --git a/packages/xo-collection/collection.event.spec.js b/packages/xo-collection/collection.event.spec.js deleted file mode 100644 index dc4759533..000000000 --- a/packages/xo-collection/collection.event.spec.js +++ /dev/null @@ -1,210 +0,0 @@ -var chai = require('chai'); -var expect = chai.expect; -var dirtyChai = require('dirty-chai'); -chai.use(dirtyChai); -var leche = require('leche'); -var sinon = require('sinon'); - -var Collection = require('./collection'); - -var col = new Collection.Collection(); - -describe('collection events', function () { - - // ============================================================ - - var data1 = { - 'primitive value': ['foo1', 1], - 'array value': ['bar1', [1,2]], - 'object value': ['baz1', {a:1, b:2}] - }; - - var addSpy; - var updateSpy; - var removeSpy; - - beforeEach(function () { - - addSpy = sinon.spy(); - updateSpy = sinon.spy(); - removeSpy = sinon.spy(); - col.on('add', addSpy); - col.on('update', updateSpy); - col.on('remove', removeSpy); - - }); - - afterEach(function () { - - col.removeAllListeners(); - - }); - - // Collection is empty ======================================================= - - describe('add', function () { - - leche.withData(data1, function (key, value) { - - it('Emits an add event transporting the key and value', function () { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.add(key, value)).to.eql(col); - expect(addSpy.called).to.be.true(); - expect(addSpy.calledWith({key: value})).to.be.true(); - - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - }); - - }); - - }); - - var updateData1 = { - 'primitive value': ['foo1', 3], - 'array value': ['bar1', [3,4]], - 'object value': ['baz1', {c:2, d:4}] - }; - - // Collection contains data1 ================================================= - - describe('update', function () { - - leche.withData(updateData1, function (key, value) { - - it('Emits an update event transporting the key and value', function () { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.update(key, value)).to.eql(col); - expect(updateSpy.called).to.be.true(); - expect(updateSpy.calledWith({key: value})).to.be.true(); - - expect(addSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - }); - - }); - - }); - - var data2 = { - 'primitive value': ['foo2', 1], - 'array value': ['bar2', [1,2]], - 'object value': ['baz2', {a:1, b:2}] - }; - - // Collection contains data1 updated ========================================= - - describe('set', function () { - - leche.withData(data1, function (key, value) { - - it('Emits an update event for pre-existing keys', function () { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.update(key, value)).to.eql(col); - expect(updateSpy.called).to.be.true(); - expect(updateSpy.calledWith({key: value})).to.be.true(); - - expect(addSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - }); - - }); - - // Collection contains data1 ============================================= - - leche.withData(data2, function (key, value) { - - it('Emits an add event for unexisting keys', function () { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.add(key, value)).to.eql(col); - expect(addSpy.called).to.be.true(); - expect(addSpy.calledWith({key: value})).to.be.true(); - - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - }); - - }); - - }); - - // Collection contains data1 & data 2 ======================================== - - describe('remove', function () { - - leche.withData(data1, function (key, value) { - - it('Emits an remove event transporting the key and removed value', function () { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.remove(key)).to.eql(col); - expect(removeSpy.called).to.be.true(); - expect(removeSpy.calledWith({key: value})).to.be.true(); - - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - }); - - }); - - }); - - // Collection contains data 2 ================================================ - - describe('clear', function () { - - var clearedData; - - it('Emits a remove event', function() { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.clear()).to.eq(col); - expect(removeSpy.calledOnce).to.be.true(); - - clearedData = removeSpy.lastCall.args[0]; - - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - }); - - it('Emits no event if collection is empty', function() { - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - - expect(col.clear()).to.eq(col); - - expect(addSpy.called).to.be.false(); - expect(updateSpy.called).to.be.false(); - expect(removeSpy.called).to.be.false(); - }); - - leche.withData(data2, function (key, value) { - - it('Emits a remove event with all cleared data', function () { - - expect(clearedData[key]).to.eq(value); - - }); - - }); - - }); - -}); \ No newline at end of file diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index d22981358..3532f4f99 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -1,273 +1,197 @@ -import makeError from 'make-error'; -import events from 'events'; -import _forEach from 'lodash.foreach'; - -const AlreadyBuffering = makeError('AlreadyBuffering'); -const NotBuffering = makeError('NotBuffering'); -const IllegalAdd = makeError('IllegalAdd'); -const DuplicateEntry = makeError('DuplicateEntry'); -const NoSuchEntry = makeError('NoSuchEntry'); - -class Collection extends events.EventEmitter { - - constructor () { - - super(); - - this._map = {}; - this._buffering = false; - this._size = 0; - - } - - bufferChanges () { - - if (this._buffering) { - throw new AlreadyBuffering('Already buffering'); // FIXME Really ?... - } - - this._buffering = true; - this._buffer = {}; - - return () => { - - if (!this._buffering) { - throw new NotBuffering('Nothing to flush'); // FIXME Really ? - } - - this._buffering = false; // FIXME Really ? - - let data = { - add: {data: {}}, - update: {data: {}}, - remove: {data: {}} - }; - - for (let key in this._buffer) { - data[this._buffer[key]].data[key] = this.has(key) ? - this.get(key) : - null; // 'remove' case - data[this._buffer[key]].has = true; - } - - ['add', 'update', 'remove'].forEach(action => { - if (data[action].has) { - this.emit(action, data[action].data); - } - }); - - delete this._buffer; - - }; - - } - - _touch (action, key, value) { - - if (this._buffering) { - - switch(action) { - - case 'add': - this._buffer[key] = this._buffer[key] ? 'update' : 'add'; - break; - case 'update': - this._buffer[key] = this._buffer[key] || 'update'; - break; - case 'remove': - switch(this._buffer[key]) { - case undefined: - case 'update': - this._buffer[key] = 'remove'; - break; - case 'add': - delete this._buffer[key]; - break; - - } - break; - } - - - } else { - - this.emit(action, {key: value}); - - } - - } - - getId (item) { - - return item.id; - - } - - has (key) { - - return Object.hasOwnProperty.call(this._map, key); - - } - - resolveEntry (keyOrObjectWithId, valueIfKey = null) { - - let value; - let key = (undefined !== keyOrObjectWithId) ? - this.getId(keyOrObjectWithId) : - undefined; - - if (undefined === key) { - if (arguments.length < 2) { - throw new IllegalAdd(); - } else { - key = keyOrObjectWithId; - value = valueIfKey; - } - } else { - value = keyOrObjectWithId; - } - - return [key, value]; - - } - - _assertHas(key) { - - if (!this.has(key)) { - throw new NoSuchEntry(); - } - - } - - _assertHasNot(key) { - - if (this.has(key)) { - throw new DuplicateEntry(); - } - - } - - add (keyOrObjectWithId, valueIfKey = null) { - - const [key, value] = this.resolveEntry.apply(this, arguments); - - this._assertHasNot(key); - - this._map[key] = value; - - this._size++; - this._touch('add', key, value); - - return this; - - } - - set (keyOrObjectWithId, valueIfKey = null) { - - const [key, value] = this.resolveEntry.apply(this, arguments); - - const action = this.has(key) ? 'update' : 'add'; - this._map[key] = value; - if ('add' === action) { - this._size++; - } - - this._touch(action, key, value); - - return this; - - } - - get (key) { - - this._assertHas(key); - - return this._map[key]; - } - - update (keyOrObjectWithId, valueIfKey = null) { - - const [key, value] = this.resolveEntry.apply(this, arguments); - - this._assertHas(key); - - this._map[key] = value; - this._touch('update', key, value); - - return this; - - } - - touch (keyOrObjectWithId) { - - const [key] = this.resolveEntry(keyOrObjectWithId, null); - - this._assertHas(key); - - if (!this._buffering) { // FIXME Really ? - // TODO throw something - } - - this._touch('update', key); - return this.get(key); - - } - - remove (keyOrObjectWithId) { - - const [key] = this.resolveEntry(keyOrObjectWithId, null); - - this._assertHas(key); - - const oldValue = this.get(key); - delete this._map[key]; - this._size--; - - // FIXME do we "emit" null in place of oldValue to harmonize with flush remove events ? - this._touch('remove', key, oldValue); - - return this; - - } - - clear () { - - if (this._size > 0) { // FIXME Really ? - if (!this._buffering) { - this.emit('remove', this._map); - } else { - for (let key in this._map) { - this._touch('remove', key); - } - } - } - - this._map = {}; - this._size = 0; - - return this; - - } - - get size () { - - return this._size; - - } - - get all () { - - return this._map; - - } - +import events from 'events' +import makeError from 'make-error' + +export const DuplicateEntry = makeError('DuplicateEntry') +export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') +export const IllegalAdd = makeError('IllegalAdd') +export const NoSuchEntry = makeError('NoSuchEntry') + +export default class Collection extends events.EventEmitter { + constructor () { + super() + + this._buffering = 0 + this._map = {} + this._size = 0 + } + + bufferChanges () { + if (this._buffering++ === 0) { + this._buffer = {} + } + + let called = false + return () => { + if (called) { + throw new BufferAlreadyFlushed('Buffer flush already requested') + } + called = true + + if (--this._buffering > 0) { + return + } + + let data = { + add: {data: {}}, + remove: {data: {}}, + update: {data: {}} + } + + for (let key in this._buffer) { + data[this._buffer[key]].data[key] = this.has(key) ? + this.get(key) : + null // "remove" case + data[this._buffer[key]].has = true + } + + ['add', 'update', 'remove'].forEach(action => { + if (data[action].has) { + this.emit(action, data[action].data) + } + }) + + delete this._buffer + } + } + + _touch (action, key) { + if (this._buffering === 0) { + process.nextTick(this.bufferChanges()) + } + switch (action) { + case 'add': + this._buffer[key] = this._buffer[key] ? 'update' : 'add' + break + case 'remove': + switch (this._buffer[key]) { + case undefined: + case 'update': + this._buffer[key] = 'remove' + break + case 'add': + delete this._buffer[key] + break + } + break + case 'update': + this._buffer[key] = this._buffer[key] || 'update' + break + } + } + + getId (item) { + return item.id + } + + has (key) { + return Object.hasOwnProperty.call(this._map, key) + } + + resolveEntry (keyOrObjectWithId, valueIfKey = null) { + let value + let key = (undefined !== keyOrObjectWithId) ? + this.getId(keyOrObjectWithId) : + undefined + + if (undefined === key) { + if (arguments.length < 2) { + throw new IllegalAdd('Missing value, or object value does not provide id/key') + } else { + key = keyOrObjectWithId + value = valueIfKey + } + } else { + value = keyOrObjectWithId + } + + return [key, value] + } + + _assertHas (key) { + if (!this.has(key)) { + throw new NoSuchEntry('No ' + key + ' entry') + } + } + + _assertHasNot (key) { + if (this.has(key)) { + throw new DuplicateEntry('Attempt to duplicate ' + key + ' entry') + } + } + + add (keyOrObjectWithId, valueIfKey = null) { + const [key, value] = this.resolveEntry.apply(this, arguments) + this._assertHasNot(key) + + this._map[key] = value + this._size++ + this._touch('add', key) + + return this + } + + set (keyOrObjectWithId, valueIfKey = null) { + const [key, value] = this.resolveEntry.apply(this, arguments) + + const action = this.has(key) ? 'update' : 'add' + this._map[key] = value + if (action === 'add') { + this._size++ + } + this._touch(action, key) + + return this + } + + get (key) { + this._assertHas(key) + return this._map[key] + } + + update (keyOrObjectWithId, valueIfKey = null) { + const [key, value] = this.resolveEntry.apply(this, arguments) + this._assertHas(key) + + this._map[key] = value + this._touch('update', key) + + return this + } + + touch (keyOrObjectWithId) { + const [key] = this.resolveEntry(keyOrObjectWithId, null) + this._assertHas(key) + + this._touch('update', key) + + return this.get(key) + } + + remove (keyOrObjectWithId) { + const [key] = this.resolveEntry(keyOrObjectWithId, null) + this._assertHas(key) + + delete this._map[key] + this._size-- + this._touch('remove', key) + + return this + } + + clear () { + for (let key in this._map) { + delete this._map[key] + this._size-- + this._touch('remove', key) + } + return this + } + + get size () { + return this._size + } + + get all () { + return this._map + } } - -export default { - Collection, - AlreadyBuffering, - NotBuffering, - IllegalAdd, - DuplicateEntry, - NoSuchEntry -}; \ No newline at end of file diff --git a/packages/xo-collection/collection.spec.js b/packages/xo-collection/collection.spec.js deleted file mode 100644 index f682b2291..000000000 --- a/packages/xo-collection/collection.spec.js +++ /dev/null @@ -1,252 +0,0 @@ -var chai = require('chai'); -var expect = chai.expect; -var dirtyChai = require('dirty-chai'); -chai.use(dirtyChai); -var leche = require('leche'); - -var Collection = require('./collection'); - -var col = new Collection.Collection(); - -describe('collection', function () { - - // Collection is empty ======================================================= - - var data1 = { - 'primitive value': ['foo1', 1], - 'array value': ['bar1', [1,2]], - 'object value': ['baz1', {a:1, b:2}] - }; - - describe('add', function () { - - leche.withData(data1, function (key, value) { - - it('Adds a new entry to the collection', function () { - expect(col.add(key, value)).to.eql(col); - }); - - }); - - leche.withData(data1, function (key, value) { - - it('We cannot add on a pre-existing key', function () { - expect(function () { - col.add(key, value); - }).to.throw(Collection.DuplicateEntry); - }); - - }); - - }); - - // Collection contains data 1 ================================================ - - var data2 = { - 'primitive value': ['foo2', 1], - 'array value': ['bar2', [1,2]], - 'object value': ['baz2', {a:1, b:2}] - }; - - describe('set', function () { - - leche.withData(data2, function (key, value) { - - it('Sets an entry of the collection...', function () { - expect(col.set(key, value)).to.eql(col); - }); - - }); - - leche.withData(data2, function (key, value) { - - it('...would it already exists or not', function () { - expect(col.set(key, value)).to.eql(col); - }); - - }); - - }); - - // Collection contains data 1 & 2 ============================================ - - var unexistingData = { - 'Unexisting key/entry': ['wat', 'any'] - }; - - describe('get', function () { - - leche.withData(data1, function (key, value) { - - it('Returns the value of an entry of the collection...', function () { - expect(col.get(key)).to.eql(value); - }); - - }); - - leche.withData(data2, function (key, value) { - - it('Returns the value of an entry of the collection...', function () { - expect(col.get(key)).to.eql(value); - }); - - }); - - leche.withData(unexistingData, function (key) { - - it('...or throws if it does not exist', function () { - expect(function () { - col.get(key); - }).to.throw(Collection.NoSuchEntry); - }); - - }); - - }); - - // Collection contains data 1 & 2 ============================================ - - var updateData2 = { - 'primitive value': ['foo2', 3], - 'array value': ['bar2', [3,4]], - 'object value': ['baz2', {c:3, d:4}] - }; - - describe('update', function () { - - leche.withData(updateData2, function (key, value) { - - it('updates the given entries...', function () { - expect(col.update(key, value)).to.eql(col); - }); - - }); - - leche.withData(updateData2, function (key, value) { - - it('...so we can see the values we get have changed accordingly', function () { - expect(col.get(key)).to.eql(value); - }); - - }); - - leche.withData(unexistingData, function (key, value) { - - it('If the entry does not exist, updating throws', function () { - expect(function () { - col.update(key, value); - }).to.throw(Collection.NoSuchEntry); - }); - - }); - - }); - - // Collection contains data 1 & 2 updated ==================================== - - describe('remove', function () { - - leche.withData(data2, function (key) { - - it('removes the given entries...', function () { - expect(col.remove(key)).to.eql(col); - }); - - }); - - leche.withData(data2, function (key) { - - it('...so trying to get them again throws...', function () { - expect(function () { - col.get(key); - }).to.throw(Collection.NoSuchEntry); - }); - - }); - - leche.withData(data2, function (key) { - - it('...and trying to remove them again also throws', function () { - expect(function () { - col.remove(key); - }).to.throw(Collection.NoSuchEntry); - }); - - }); - - }); - - // Collection contains data 1 ================================================ - - describe('has', function () { - - leche.withData(data1, function (key) { - - it('Tells us if an entry exists...', function () { - expect(col.has(key)).to.be.true(); - }); - - }); - - leche.withData(data2, function (key) { - - it('...or not', function () { - expect(col.has(key)).to.be.false(); - }); - - }); - - }); - - // Collection contains data 1 ================================================ - - describe('size', function () { - - it('Reveals the number of existing entries', function () { - expect(col.size).to.eq(Object.keys(data1).length); - }); - - }); - - // Collection contains data 1 ================================================ - - describe('all', function () { - - leche.withData(data1, function (key, value) { - - it('Gives access to the internal collection...', function () { - expect(col.all).to.have.ownProperty(key); - expect(col.all[key]).to.eq(value); - }); - - }); - - leche.withData(data2, function (key) { - - it('Gives access to the internal collection...', function () { - expect(col.all).to.not.have.ownProperty(key); - expect(col.all[key]).to.eq(undefined); - }); - - }); - - it('Gives access to the internal collection...', function () { - expect(col.size).to.eq(Object.keys(col.all).length); - }); - - }); - - // Collection contains data 1 ================================================ - - describe('clear', function () { - - it('wipes out all the collection', function () { - expect(col.clear()).to.eq(col); - - expect(col.size).to.eq(0); - expect(col.all).to.eql({}); - }); - - }); - -}); \ No newline at end of file diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 22a0312ab..e5a0525bd 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -11,6 +11,7 @@ "babel": "^4.7.16", "chai": "^2.2.0", "dirty-chai": "^1.2.0", + "event-to-promise": "^0.3.2", "leche": "^2.1.1", "mocha": "^2.2.1", "sinon": "^1.14.1" From dd1d16f91c0ed0d87f643b98f997f5f88a116b0a Mon Sep 17 00:00:00 2001 From: Fabrice Marsaud Date: Thu, 2 Apr 2015 16:49:40 +0200 Subject: [PATCH 013/103] Fixes and enhancements --- packages/xo-collection/collection.js | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/collection.js index 3532f4f99..4dcc9d4d9 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/collection.js @@ -5,19 +5,20 @@ export const DuplicateEntry = makeError('DuplicateEntry') export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') export const IllegalAdd = makeError('IllegalAdd') export const NoSuchEntry = makeError('NoSuchEntry') +export const IllegalTouch = makeError('IllegalTouch') export default class Collection extends events.EventEmitter { constructor () { super() this._buffering = 0 - this._map = {} + this._map = Object.create(null) this._size = 0 } bufferChanges () { if (this._buffering++ === 0) { - this._buffer = {} + this._buffer = Object.create(null) } let called = false @@ -87,7 +88,7 @@ export default class Collection extends events.EventEmitter { return Object.hasOwnProperty.call(this._map, key) } - resolveEntry (keyOrObjectWithId, valueIfKey = null) { + _resolveEntry (keyOrObjectWithId, valueIfKey = null) { let value let key = (undefined !== keyOrObjectWithId) ? this.getId(keyOrObjectWithId) : @@ -120,7 +121,7 @@ export default class Collection extends events.EventEmitter { } add (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this.resolveEntry.apply(this, arguments) + const [key, value] = this._resolveEntry.apply(this, arguments) this._assertHasNot(key) this._map[key] = value @@ -131,7 +132,7 @@ export default class Collection extends events.EventEmitter { } set (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this.resolveEntry.apply(this, arguments) + const [key, value] = this._resolveEntry.apply(this, arguments) const action = this.has(key) ? 'update' : 'add' this._map[key] = value @@ -143,13 +144,16 @@ export default class Collection extends events.EventEmitter { return this } - get (key) { + get (key, defaultValue) { + if (arguments.length > 1 && !this.has(key)) { + return defaultValue + } this._assertHas(key) return this._map[key] } update (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this.resolveEntry.apply(this, arguments) + const [key, value] = this._resolveEntry.apply(this, arguments) this._assertHas(key) this._map[key] = value @@ -159,8 +163,12 @@ export default class Collection extends events.EventEmitter { } touch (keyOrObjectWithId) { - const [key] = this.resolveEntry(keyOrObjectWithId, null) + const [key] = this._resolveEntry(keyOrObjectWithId, null) this._assertHas(key) + let value = this.get(key) + if (typeof value !== 'object' || value === null) { + throw new IllegalTouch('Touching a scalar. Not an object') + } this._touch('update', key) @@ -168,7 +176,7 @@ export default class Collection extends events.EventEmitter { } remove (keyOrObjectWithId) { - const [key] = this.resolveEntry(keyOrObjectWithId, null) + const [key] = this._resolveEntry(keyOrObjectWithId, null) this._assertHas(key) delete this._map[key] From 5ba74936133072f52e14b707018af758803a50ff Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 7 Apr 2015 18:01:33 +0200 Subject: [PATCH 014/103] Better repo architecture. --- packages/xo-collection/.editorconfig | 65 +++++++ packages/xo-collection/.gitignore | 31 +-- packages/xo-collection/.npmignore | 2 + packages/xo-collection/.travis.yml | 5 + packages/xo-collection/README.md | 184 +++++++++++++++++- packages/xo-collection/package.json | 46 ++++- .../{collection.js => src/index.js} | 4 +- .../index.spec.js} | 5 +- packages/xo-collection/test.js | 81 -------- 9 files changed, 299 insertions(+), 124 deletions(-) create mode 100644 packages/xo-collection/.editorconfig create mode 100644 packages/xo-collection/.npmignore create mode 100644 packages/xo-collection/.travis.yml rename packages/xo-collection/{collection.js => src/index.js} (100%) rename packages/xo-collection/{collection.async.spec.js => src/index.spec.js} (96%) delete mode 100644 packages/xo-collection/test.js diff --git a/packages/xo-collection/.editorconfig b/packages/xo-collection/.editorconfig new file mode 100644 index 000000000..da21ef4c5 --- /dev/null +++ b/packages/xo-collection/.editorconfig @@ -0,0 +1,65 @@ +# http://EditorConfig.org +# +# Julien Fontanet's configuration +# https://gist.github.com/julien-f/8096213 + +# Top-most EditorConfig file. +root = true + +# Common config. +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespaces = true + +# CoffeeScript +# +# https://github.com/polarmobile/coffeescript-style-guide/blob/master/README.md +[*.{,lit}coffee] +indent_size = 2 +indent_style = space + +# Markdown +[*.{md,mdwn,mdown,markdown}] +indent_size = 4 +indent_style = space + +# Package.json +# +# This indentation style is the one used by npm. +[/package.json] +indent_size = 2 +indent_style = space + +# Jade +[*.jade] +indent_size = 2 +indent_style = space + +# JavaScript +# +# Two spaces seems to be the standard most common style, at least in +# Node.js (http://nodeguide.com/style.html#tabs-vs-spaces). +[*.js] +indent_size = 2 +indent_style = space + +# Less +[*.less] +indent_size = 2 +indent_style = space + +# Sass +# +# Style used for http://libsass.com +[*.s[ac]ss] +indent_size = 2 +indent_style = space + +# YAML +# +# Only spaces are allowed. +[*.yaml] +indent_size = 2 +indent_style = space diff --git a/packages/xo-collection/.gitignore b/packages/xo-collection/.gitignore index 59d842baa..a4a5666f8 100644 --- a/packages/xo-collection/.gitignore +++ b/packages/xo-collection/.gitignore @@ -1,28 +1,7 @@ -# Logs -logs -*.log +/bower_components/ +/dist/ -# Runtime data -pids -*.pid -*.seed +npm-debug.log -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -# Commenting this out is preferred by some people, see -# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- -node_modules - -# Users Environment Variables -.lock-wscript +!node_modules/* +node_modules/*/ diff --git a/packages/xo-collection/.npmignore b/packages/xo-collection/.npmignore new file mode 100644 index 000000000..5f4b80cec --- /dev/null +++ b/packages/xo-collection/.npmignore @@ -0,0 +1,2 @@ +*.spec.js +*.spec.js.map diff --git a/packages/xo-collection/.travis.yml b/packages/xo-collection/.travis.yml new file mode 100644 index 000000000..5227e1127 --- /dev/null +++ b/packages/xo-collection/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 'iojs' + - '0.12' + - '0.10' \ No newline at end of file diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index abef15571..82bb27f97 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -1,2 +1,182 @@ -# collection -A collection class with a batch feature with commit/rollback/replay +# collection [![Build Status](https://travis-ci.org/marsaud/collection.png?branch=master)](https://travis-ci.org/marsaud/collection) + +> Generic in-memory collection with events + +## Install + +Installation of the [npm package](https://npmjs.org/package/collection): + +``` +> npm install --save collection +``` + +## Usage + +```javascript +var Collection = require('collection') +``` + +### Creation + +```javascript +// Creates a new collection. +var col = new Collection() +``` + +### Manipulation + +**Inserting a new entry** + +```javascript +col.add('foo', true) +``` + +**Updating an existing entry** + +```javascript +col.update('foo', false) +``` + +**Inserting or updating an entry** + +```javascript +col.set('bar', true) +``` + +**Notifying an external update** + +> If an entry is an object, it can be updated directly without using +> the `set`/`update` methods. +> +> To make sure the collection stay in sync and the correct events are +> sent, the `touch` method can be used to notify the change. + +```javascript +var baz = {} + +col.add('baz', baz) + +baz.prop = true +col.touch('baz') +``` + +> Because this is a much used pattern, `touch` returns the entry to +> allow its direct modification. + +```javascript +col.touch('baz').prop = false +``` + +**Removing an existing entry** + +```javascript +col.unset('bar') +``` + +**Removing all entries** + +```javascript +col.clear() +``` + +### Query + +**Checking the existence of an entry** + +```javascript +var hasBar = col.has('bar') +``` + +**Getting an existing entry** + +```javascript +var foo = col.get('foo') + +// The second parameter can be used to specify a fallback in case the +// entry does not exist. +var bar = col.get('bar', 6.28) +``` + +**Getting the number of entries** + +```javascript +var size = col.size +``` + +### Events + +> The events are emitted asynchronously (at the next turn/tick of the +> event loop) and are deduplicated which means, for instance, that an +> addition followed by an update will result only in a single +> addition. + +**New entries** + +```javascript +col.on('add', (added) => { + forEach(added, (value, key) => { + console.log('+ %s: %j', key, value) + }) +}) +``` + +**Updated entries** + +```javascript +col.on('update', (updated) => { + forEach(updated, (value, key) => { + console.log('- %s: %j', key, value) + }) +}) +``` + +**Removed entries** + +```javascript +col.on('remove', (removed) => { + // For consistency, `removed` is also a map but contrary to `ædded` + // and `updated`, the values associated to the keys are not + // significant since the entries have already be removed. + + forEach(removed, (value, key) => { + console.log('± %s', key) + }) +}) +``` + +## Development + +### Installing dependencies + +``` +> npm install +``` + +### Compilation + +The sources files are watched and automatically recompiled on changes. + +``` +> npm run dev +``` + +### Tests + +``` +> npm run test-dev +``` + +## Contributions + +Contributions are *very* welcomed, either on the documentation or on +the code. + +You may: + +- report any [issue](https://github.com/marsaud/collection/issues) + you've encountered; +- fork and create a pull request. + +## License + +ISC © [Vates SAS](http://vates.fr) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index e5a0525bd..06d89e16f 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,24 +1,50 @@ { - "name": "xo-collection", + "private": true, + "name": "collection", "version": "0.0.0", - "description": "A generice batch collection attempt", - "main": "collection.js", + "license": "ISC", + "description": "Generic in-memory collection with events", + "keywords": [], + "homepage": "https://github.com/marsaud/collection", + "bugs": "https://github.com/marsaud/collection/issues", + "repository": { + "type": "git", + "url": "https://github.com/marsaud/collection.git" + }, + "author": { + "name": "Fabrice Marsaud", + "email": "fabrice.marsaud@vates.fr" + }, + "preferGlobal": false, + "main": "dist/", + "files": [ + "dist/" + ], "dependencies": { + "babel-runtime": "^5", "lodash.foreach": "^3.0.2", "make-error": "^0.3.0" }, "devDependencies": { - "babel": "^4.7.16", - "chai": "^2.2.0", + "babel": "^5", + "chai": "*", "dirty-chai": "^1.2.0", "event-to-promise": "^0.3.2", "leche": "^2.1.1", - "mocha": "^2.2.1", - "sinon": "^1.14.1" + "mocha": "*", + "sinon": "^1.14.1", + "standard": "*" }, "scripts": { - "test": "mocha --require babel/register *.spec.js" + "build": "mkdir --parents dist && babel --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", + "dev": "mkdir --parents dist && babel --watch --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", + "prepublish": "npm run build", + "test": "standard && npm run build && mocha 'dist/**/*.spec.js'", + "test-dev": "standard && mocha --watch --reporter=min 'dist/**/*.spec.js'" }, - "author": "Fabrice Marsaud ", - "license": "aGPLv3" + "standard": { + "ignore": [ + "dist/**" + ] + } } diff --git a/packages/xo-collection/collection.js b/packages/xo-collection/src/index.js similarity index 100% rename from packages/xo-collection/collection.js rename to packages/xo-collection/src/index.js index 4dcc9d4d9..b0ae01b95 100644 --- a/packages/xo-collection/collection.js +++ b/packages/xo-collection/src/index.js @@ -1,11 +1,11 @@ import events from 'events' import makeError from 'make-error' -export const DuplicateEntry = makeError('DuplicateEntry') export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') +export const DuplicateEntry = makeError('DuplicateEntry') export const IllegalAdd = makeError('IllegalAdd') -export const NoSuchEntry = makeError('NoSuchEntry') export const IllegalTouch = makeError('IllegalTouch') +export const NoSuchEntry = makeError('NoSuchEntry') export default class Collection extends events.EventEmitter { constructor () { diff --git a/packages/xo-collection/collection.async.spec.js b/packages/xo-collection/src/index.spec.js similarity index 96% rename from packages/xo-collection/collection.async.spec.js rename to packages/xo-collection/src/index.spec.js index a94983e60..96edd61f9 100644 --- a/packages/xo-collection/collection.async.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -1,12 +1,11 @@ /* eslint-env mocha */ -import Collection, {DuplicateEntry, NoSuchEntry} from './collection' +import Collection, {DuplicateEntry, NoSuchEntry} from './index' import eventToPromise from 'event-to-promise' import sinon from 'sinon' -import chai from 'chai' -const expect = chai.expect +import chai, {expect} from 'chai' import dirtyChai from 'dirty-chai' chai.use(dirtyChai) diff --git a/packages/xo-collection/test.js b/packages/xo-collection/test.js deleted file mode 100644 index 2ac59da7f..000000000 --- a/packages/xo-collection/test.js +++ /dev/null @@ -1,81 +0,0 @@ -import Collection from './collection'; - -let col = new Collection.Collection(); - -col.add('foo', 1); - -// An object with id property - -// ==================== -// Jouer sur le passage par référence, et la convention d'objets avec une prop ID - -let obj = {id: 'bar', content: 2}; -col.add(obj); -console.log(obj.get('bar')); -// > {id: 'bar', content: 2} - -col.bufferChanges(true); -col.update('bar').content = 4; -// update accesses obj at bar key and marks bar as updated. No event emitted. - -col.get('bar').content = 5; -obj.content = 6; -// bar is already marked as updated, so ... - -col.flush(); -// ...Emits an update as bar has been "updated to 6" - -col.bufferChanges(true); -col.update(obj).content = 7; // Short writing without knowing ID -// WARNING, do not change ID after adding ... - -col.bufferChanges(false); -col.flush(); -// No event emitted ... exception thrown ?... -col.bufferChanges(true); -col.update(obj); -col.flush(); -// Emits an update event as bar has been "updated to 7" - -// ------------------------------------------------------------ -// Special cases : -let foo = {id: 'foo'}; -let bar = {id: 'bar'}; -col.add(foo); - -try { - col.update(foo, bar); -} catch(e) { - // Throws an instant exception on ID violation - console.error(e); -} - -try { - col.udpate('foo', bar); -} catch(e) { - // Same - console.error(e); -} - -try { - col.update(foo).id = 'bar'; -} catch (e) { - // Throws an exception at Event emission (key !== content.id) - console.error(e); -} - -col.bufferChanges(true); -col.remove(foo); -col.add(foo); -col.bufferChanges(false); -// Silent...(No events) - -col.bufferChanges(true); -col.update(foo).id = 'bar'; -// Nothing happens -try { - col.flush(); -} catch (e) { - // Throws - console.log(e); -} From a40832dffd7060c92bb78a8ff9590dcfbfdec7ed Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 7 Apr 2015 18:06:17 +0200 Subject: [PATCH 015/103] Typo. --- packages/xo-collection/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 82bb27f97..16ca4daf0 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -48,7 +48,7 @@ col.set('bar', true) > If an entry is an object, it can be updated directly without using > the `set`/`update` methods. > -> To make sure the collection stay in sync and the correct events are +> To make sure the collection stays in sync and the correct events are > sent, the `touch` method can be used to notify the change. ```javascript From 23e7542871a33d490da45d100ec2675f9c116806 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 7 Apr 2015 18:15:38 +0200 Subject: [PATCH 016/103] Document Collection#all. --- packages/xo-collection/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 16ca4daf0..40265afd9 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -97,6 +97,25 @@ var foo = col.get('foo') var bar = col.get('bar', 6.28) ``` +**Getting a read-only view of the collection** + +> This property is useful for example to iterate over the collection +> or to make advanced queries with the help of utility libraries such +> as lodash. + +```javascript +var _ = require('lodash') + +// Prints all the entries. +_.forEach(col.all, function (value, key) { + console.log('- %s: %j', key, value) +}) + +// Finds all the entries which are objects and have a property +// `active` which equals `true`. +var results = _.where(col.all, { active: true }) +``` + **Getting the number of entries** ```javascript From fb9203d3966f682695c8876ba314664d39433588 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 7 Apr 2015 18:49:20 +0200 Subject: [PATCH 017/103] =?UTF-8?q?Fix=20doc:=20unset()=20=E2=86=92=20remo?= =?UTF-8?q?ve().?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/xo-collection/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 40265afd9..ca5849fec 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -70,7 +70,7 @@ col.touch('baz').prop = false **Removing an existing entry** ```javascript -col.unset('bar') +col.remove('bar') ``` **Removing all entries** From ea3219fa10af754ebf003bcac3b5693fa89cd5c3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 10:04:58 +0200 Subject: [PATCH 018/103] Typo. --- packages/xo-collection/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index ca5849fec..6d30a9776 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -144,7 +144,7 @@ col.on('add', (added) => { ```javascript col.on('update', (updated) => { forEach(updated, (value, key) => { - console.log('- %s: %j', key, value) + console.log('± %s: %j', key, value) }) }) ``` @@ -153,12 +153,12 @@ col.on('update', (updated) => { ```javascript col.on('remove', (removed) => { - // For consistency, `removed` is also a map but contrary to `ædded` + // For consistency, `removed` is also a map but contrary to `added` // and `updated`, the values associated to the keys are not // significant since the entries have already be removed. forEach(removed, (value, key) => { - console.log('± %s', key) + console.log('- %s', key) }) }) ``` From 0ea662d8fee2b73600aaf452cbd7fb8842eae6c5 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 10:05:41 +0200 Subject: [PATCH 019/103] Replace let by const where possible. --- packages/xo-collection/src/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index b0ae01b95..2221dfaab 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -32,7 +32,7 @@ export default class Collection extends events.EventEmitter { return } - let data = { + const data = { add: {data: {}}, remove: {data: {}}, update: {data: {}} @@ -165,7 +165,7 @@ export default class Collection extends events.EventEmitter { touch (keyOrObjectWithId) { const [key] = this._resolveEntry(keyOrObjectWithId, null) this._assertHas(key) - let value = this.get(key) + const value = this.get(key) if (typeof value !== 'object' || value === null) { throw new IllegalTouch('Touching a scalar. Not an object') } From eeb898179e2f75413bd7fc33183b5c599747a93b Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 10:42:00 +0200 Subject: [PATCH 020/103] Minor simplification of buffer flushing. --- packages/xo-collection/src/index.js | 39 ++++++++++++++---------- packages/xo-collection/src/index.spec.js | 2 +- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 2221dfaab..a3415c770 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -1,4 +1,4 @@ -import events from 'events' +import {EventEmitter} from 'events' import makeError from 'make-error' export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') @@ -7,19 +7,27 @@ export const IllegalAdd = makeError('IllegalAdd') export const IllegalTouch = makeError('IllegalTouch') export const NoSuchEntry = makeError('NoSuchEntry') -export default class Collection extends events.EventEmitter { +function isNotEmpty (map) { + /* eslint no-unused-vars: 0*/ + + for (let key in map) { + return true + } + return false +} + +export default class Collection extends EventEmitter { constructor () { super() + this._buffer = Object.create(null) this._buffering = 0 this._map = Object.create(null) this._size = 0 } bufferChanges () { - if (this._buffering++ === 0) { - this._buffer = Object.create(null) - } + ++this._buffering let called = false return () => { @@ -28,30 +36,29 @@ export default class Collection extends events.EventEmitter { } called = true - if (--this._buffering > 0) { + if (--this._buffering) { return } const data = { - add: {data: {}}, - remove: {data: {}}, - update: {data: {}} + add: Object.create(null), + remove: Object.create(null), + update: Object.create(null) } for (let key in this._buffer) { - data[this._buffer[key]].data[key] = this.has(key) ? - this.get(key) : - null // "remove" case - data[this._buffer[key]].has = true + data[this._buffer[key]][key] = this._map[key] } ['add', 'update', 'remove'].forEach(action => { - if (data[action].has) { - this.emit(action, data[action].data) + const entries = data[action] + + if (isNotEmpty(entries)) { + this.emit(action, entries) } }) - delete this._buffer + this._buffer = Object.create(null) } } diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 96edd61f9..399b90e92 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -81,7 +81,7 @@ describe('Collection', function () { // Async event. return eventToPromise(this.col, 'remove').then(function (removed) { expect(removed).to.have.all.keys('bar') - expect(removed.bar).to.equal(null) + expect(removed.bar).to.not.exist() }) }) From 6c8330845188798986d3b3bbca3c2654f47ac576 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 10:48:27 +0200 Subject: [PATCH 021/103] Optimize Collection#get(). --- packages/xo-collection/src/index.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index a3415c770..dc446409c 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -152,11 +152,16 @@ export default class Collection extends EventEmitter { } get (key, defaultValue) { - if (arguments.length > 1 && !this.has(key)) { + if (this.has(key)) { + return this._map[key] + } + + if (arguments.length > 1) { return defaultValue } + + // Throws a NoSuchEntry. this._assertHas(key) - return this._map[key] } update (keyOrObjectWithId, valueIfKey = null) { From 5e0c4d7b7a4017f86c203a0101e27fea46839f69 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 10:50:04 +0200 Subject: [PATCH 022/103] Avoid Function#apply() for performance. --- packages/xo-collection/src/index.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index dc446409c..39c2fc270 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -128,7 +128,7 @@ export default class Collection extends EventEmitter { } add (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this._resolveEntry.apply(this, arguments) + const [key, value] = this._resolveEntry(keyOrObjectWithId, valueIfKey) this._assertHasNot(key) this._map[key] = value @@ -139,7 +139,7 @@ export default class Collection extends EventEmitter { } set (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this._resolveEntry.apply(this, arguments) + const [key, value] = this._resolveEntry(keyOrObjectWithId, valueIfKey) const action = this.has(key) ? 'update' : 'add' this._map[key] = value @@ -165,7 +165,7 @@ export default class Collection extends EventEmitter { } update (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this._resolveEntry.apply(this, arguments) + const [key, value] = this._resolveEntry(keyOrObjectWithId, valueIfKey) this._assertHas(key) this._map[key] = value From b70e0e3e2b2ee751c9a7baa43522901ddd42a918 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 11:40:07 +0200 Subject: [PATCH 023/103] Tests for #add(), #update(), #set() and #remove() with an object. --- packages/xo-collection/src/index.spec.js | 40 +++++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 399b90e92..89f5bfb71 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -24,7 +24,7 @@ describe('Collection', function () { this.col.add('foo', true) - expect(this.col.get('foo')).to.equal(true) + expect(this.col.get('foo')).to.be.true() // No sync events. sinon.assert.notCalled(spy) @@ -32,13 +32,21 @@ describe('Collection', function () { // Async event. return eventToPromise(this.col, 'add').then(function (added) { expect(added).to.have.all.keys('foo') - expect(added.foo).to.equal(true) + expect(added.foo).to.be.true() }) }) it('throws an exception if the item already exists', function () { expect(() => this.col.add('bar', true)).to.throw(DuplicateEntry) }) + + it('accepts an object with an id property', function () { + const foo = { id: 'foo' } + + this.col.add(foo) + + expect(this.col.get(foo.id)).to.equal(foo) + }) }) describe('#update()', function () { @@ -64,6 +72,14 @@ describe('Collection', function () { it('throws an exception if the item does not exist', function () { expect(() => this.col.update('baz', true)).to.throw(NoSuchEntry) }) + + it('accepts an object with an id property', function () { + const bar = { id: 'bar' } + + this.col.update(bar) + + expect(this.col.get(bar.id)).to.equal(bar) + }) }) describe('#remove()', function () { @@ -88,6 +104,14 @@ describe('Collection', function () { it('throws an exception if the item does not exist', function () { expect(() => this.col.remove('baz', true)).to.throw(NoSuchEntry) }) + + it('accepts an object with an id property', function () { + const bar = { id: 'bar' } + + this.col.remove(bar) + + expect(this.col.has(bar.id)).to.be.false() + }) }) describe('#set()', function () { @@ -97,7 +121,7 @@ describe('Collection', function () { this.col.set('foo', true) - expect(this.col.get('foo')).to.equal(true) + expect(this.col.get('foo')).to.be.true() // No sync events. sinon.assert.notCalled(spy) @@ -105,7 +129,7 @@ describe('Collection', function () { // Async events. return eventToPromise(this.col, 'add').then(function (added) { expect(added).to.have.all.keys('foo') - expect(added.foo).to.equal(true) + expect(added.foo).to.be.true() }) }) @@ -126,6 +150,14 @@ describe('Collection', function () { expect(updated.bar).to.equal(1) }) }) + + it('accepts an object with an id property', function () { + const foo = { id: 'foo' } + + this.col.set(foo) + + expect(this.col.get(foo.id)).to.equal(foo) + }) }) }) From 0303558ae173436303298aeba3694895aa779d4f Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 11:49:25 +0200 Subject: [PATCH 024/103] Prefer the term of item over entry. --- packages/xo-collection/README.md | 34 ++++++++-------- packages/xo-collection/src/index.js | 50 ++++++++++++------------ packages/xo-collection/src/index.spec.js | 8 ++-- 3 files changed, 46 insertions(+), 46 deletions(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 6d30a9776..c49b2f59e 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -25,19 +25,19 @@ var col = new Collection() ### Manipulation -**Inserting a new entry** +**Inserting a new item** ```javascript col.add('foo', true) ``` -**Updating an existing entry** +**Updating an existing item** ```javascript col.update('foo', false) ``` -**Inserting or updating an entry** +**Inserting or updating an item** ```javascript col.set('bar', true) @@ -45,7 +45,7 @@ col.set('bar', true) **Notifying an external update** -> If an entry is an object, it can be updated directly without using +> If an item is an object, it can be updated directly without using > the `set`/`update` methods. > > To make sure the collection stays in sync and the correct events are @@ -60,20 +60,20 @@ baz.prop = true col.touch('baz') ``` -> Because this is a much used pattern, `touch` returns the entry to +> Because this is a much used pattern, `touch` returns the item to > allow its direct modification. ```javascript col.touch('baz').prop = false ``` -**Removing an existing entry** +**Removing an existing item** ```javascript col.remove('bar') ``` -**Removing all entries** +**Removing all items** ```javascript col.clear() @@ -81,19 +81,19 @@ col.clear() ### Query -**Checking the existence of an entry** +**Checking the existence of an item** ```javascript var hasBar = col.has('bar') ``` -**Getting an existing entry** +**Getting an existing item** ```javascript var foo = col.get('foo') // The second parameter can be used to specify a fallback in case the -// entry does not exist. +// item does not exist. var bar = col.get('bar', 6.28) ``` @@ -106,17 +106,17 @@ var bar = col.get('bar', 6.28) ```javascript var _ = require('lodash') -// Prints all the entries. +// Prints all the items. _.forEach(col.all, function (value, key) { console.log('- %s: %j', key, value) }) -// Finds all the entries which are objects and have a property +// Finds all the items which are objects and have a property // `active` which equals `true`. var results = _.where(col.all, { active: true }) ``` -**Getting the number of entries** +**Getting the number of items** ```javascript var size = col.size @@ -129,7 +129,7 @@ var size = col.size > addition followed by an update will result only in a single > addition. -**New entries** +**New items** ```javascript col.on('add', (added) => { @@ -139,7 +139,7 @@ col.on('add', (added) => { }) ``` -**Updated entries** +**Updated items** ```javascript col.on('update', (updated) => { @@ -149,13 +149,13 @@ col.on('update', (updated) => { }) ``` -**Removed entries** +**Removed items** ```javascript col.on('remove', (removed) => { // For consistency, `removed` is also a map but contrary to `added` // and `updated`, the values associated to the keys are not - // significant since the entries have already be removed. + // significant since the items have already be removed. forEach(removed, (value, key) => { console.log('- %s', key) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 39c2fc270..55a13ff31 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -2,10 +2,10 @@ import {EventEmitter} from 'events' import makeError from 'make-error' export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') -export const DuplicateEntry = makeError('DuplicateEntry') +export const DuplicateItem = makeError('DuplicateItem') export const IllegalAdd = makeError('IllegalAdd') export const IllegalTouch = makeError('IllegalTouch') -export const NoSuchEntry = makeError('NoSuchEntry') +export const NoSuchItem = makeError('NoSuchItem') function isNotEmpty (map) { /* eslint no-unused-vars: 0*/ @@ -22,7 +22,7 @@ export default class Collection extends EventEmitter { this._buffer = Object.create(null) this._buffering = 0 - this._map = Object.create(null) + this._items = Object.create(null) this._size = 0 } @@ -47,14 +47,14 @@ export default class Collection extends EventEmitter { } for (let key in this._buffer) { - data[this._buffer[key]][key] = this._map[key] + data[this._buffer[key]][key] = this._items[key] } ['add', 'update', 'remove'].forEach(action => { - const entries = data[action] + const items = data[action] - if (isNotEmpty(entries)) { - this.emit(action, entries) + if (isNotEmpty(items)) { + this.emit(action, items) } }) @@ -92,10 +92,10 @@ export default class Collection extends EventEmitter { } has (key) { - return Object.hasOwnProperty.call(this._map, key) + return Object.hasOwnProperty.call(this._items, key) } - _resolveEntry (keyOrObjectWithId, valueIfKey = null) { + _resolveItem (keyOrObjectWithId, valueIfKey = null) { let value let key = (undefined !== keyOrObjectWithId) ? this.getId(keyOrObjectWithId) : @@ -117,21 +117,21 @@ export default class Collection extends EventEmitter { _assertHas (key) { if (!this.has(key)) { - throw new NoSuchEntry('No ' + key + ' entry') + throw new NoSuchItem('No ' + key + ' item') } } _assertHasNot (key) { if (this.has(key)) { - throw new DuplicateEntry('Attempt to duplicate ' + key + ' entry') + throw new DuplicateItem('Attempt to duplicate ' + key + ' item') } } add (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this._resolveEntry(keyOrObjectWithId, valueIfKey) + const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) this._assertHasNot(key) - this._map[key] = value + this._items[key] = value this._size++ this._touch('add', key) @@ -139,10 +139,10 @@ export default class Collection extends EventEmitter { } set (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this._resolveEntry(keyOrObjectWithId, valueIfKey) + const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) const action = this.has(key) ? 'update' : 'add' - this._map[key] = value + this._items[key] = value if (action === 'add') { this._size++ } @@ -153,29 +153,29 @@ export default class Collection extends EventEmitter { get (key, defaultValue) { if (this.has(key)) { - return this._map[key] + return this._items[key] } if (arguments.length > 1) { return defaultValue } - // Throws a NoSuchEntry. + // Throws a NoSuchItem. this._assertHas(key) } update (keyOrObjectWithId, valueIfKey = null) { - const [key, value] = this._resolveEntry(keyOrObjectWithId, valueIfKey) + const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) this._assertHas(key) - this._map[key] = value + this._items[key] = value this._touch('update', key) return this } touch (keyOrObjectWithId) { - const [key] = this._resolveEntry(keyOrObjectWithId, null) + const [key] = this._resolveItem(keyOrObjectWithId, null) this._assertHas(key) const value = this.get(key) if (typeof value !== 'object' || value === null) { @@ -188,10 +188,10 @@ export default class Collection extends EventEmitter { } remove (keyOrObjectWithId) { - const [key] = this._resolveEntry(keyOrObjectWithId, null) + const [key] = this._resolveItem(keyOrObjectWithId, null) this._assertHas(key) - delete this._map[key] + delete this._items[key] this._size-- this._touch('remove', key) @@ -199,8 +199,8 @@ export default class Collection extends EventEmitter { } clear () { - for (let key in this._map) { - delete this._map[key] + for (let key in this._items) { + delete this._items[key] this._size-- this._touch('remove', key) } @@ -212,6 +212,6 @@ export default class Collection extends EventEmitter { } get all () { - return this._map + return this._items } } diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 89f5bfb71..1e6fdfe70 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import Collection, {DuplicateEntry, NoSuchEntry} from './index' +import Collection, {DuplicateItem, NoSuchItem} from './index' import eventToPromise from 'event-to-promise' import sinon from 'sinon' @@ -37,7 +37,7 @@ describe('Collection', function () { }) it('throws an exception if the item already exists', function () { - expect(() => this.col.add('bar', true)).to.throw(DuplicateEntry) + expect(() => this.col.add('bar', true)).to.throw(DuplicateItem) }) it('accepts an object with an id property', function () { @@ -70,7 +70,7 @@ describe('Collection', function () { }) it('throws an exception if the item does not exist', function () { - expect(() => this.col.update('baz', true)).to.throw(NoSuchEntry) + expect(() => this.col.update('baz', true)).to.throw(NoSuchItem) }) it('accepts an object with an id property', function () { @@ -102,7 +102,7 @@ describe('Collection', function () { }) it('throws an exception if the item does not exist', function () { - expect(() => this.col.remove('baz', true)).to.throw(NoSuchEntry) + expect(() => this.col.remove('baz', true)).to.throw(NoSuchItem) }) it('accepts an object with an id property', function () { From 45441653f6f75aa6ae6d66c0c2a8edc167809f7b Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 11:51:18 +0200 Subject: [PATCH 025/103] =?UTF-8?q?#bufferChanges()=20=E2=86=92=20#bufferE?= =?UTF-8?q?vents().?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/xo-collection/src/index.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 55a13ff31..82fd0bbcf 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -26,7 +26,7 @@ export default class Collection extends EventEmitter { this._size = 0 } - bufferChanges () { + bufferEvents () { ++this._buffering let called = false @@ -64,7 +64,9 @@ export default class Collection extends EventEmitter { _touch (action, key) { if (this._buffering === 0) { - process.nextTick(this.bufferChanges()) + const flush = this.bufferEvents() + + process.nextTick(flush) } switch (action) { case 'add': From f479e914bbb02dafccc2d904836f445440487454 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 11:58:46 +0200 Subject: [PATCH 026/103] #getId() should behave even if the item is null or undefined. --- packages/xo-collection/src/index.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 82fd0bbcf..49e5dd804 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -90,7 +90,7 @@ export default class Collection extends EventEmitter { } getId (item) { - return item.id + return item && item.id } has (key) { @@ -99,9 +99,7 @@ export default class Collection extends EventEmitter { _resolveItem (keyOrObjectWithId, valueIfKey = null) { let value - let key = (undefined !== keyOrObjectWithId) ? - this.getId(keyOrObjectWithId) : - undefined + let key = this.getId(keyOrObjectWithId) if (undefined === key) { if (arguments.length < 2) { From bab2de36adacff4bb5b54351c8e00c30e834a55a Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 14:24:07 +0200 Subject: [PATCH 027/103] Tests for events deduplication. --- packages/xo-collection/package.json | 3 +- packages/xo-collection/src/index.spec.js | 104 ++++++++++++++++++++++- 2 files changed, 103 insertions(+), 4 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 06d89e16f..c80b2adb9 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -22,7 +22,6 @@ ], "dependencies": { "babel-runtime": "^5", - "lodash.foreach": "^3.0.2", "make-error": "^0.3.0" }, "devDependencies": { @@ -30,7 +29,7 @@ "chai": "*", "dirty-chai": "^1.2.0", "event-to-promise": "^0.3.2", - "leche": "^2.1.1", + "lodash.foreach": "^3.0.2", "mocha": "*", "sinon": "^1.14.1", "standard": "*" diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 1e6fdfe70..ed7edb385 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -3,18 +3,34 @@ import Collection, {DuplicateItem, NoSuchItem} from './index' import eventToPromise from 'event-to-promise' +import forEach from 'lodash.foreach' import sinon from 'sinon' import chai, {expect} from 'chai' import dirtyChai from 'dirty-chai' chai.use(dirtyChai) +function waitTicks (n = 1) { + const {nextTick} = process + + return new Promise(function (resolve) { + (function waitNextTick () { + // The first tick is handled by Promise#then() + if (--n) { + nextTick(waitNextTick) + } else { + resolve() + } + })() + }) +} + describe('Collection', function () { - beforeEach(function (done) { + beforeEach(function () { this.col = new Collection() this.col.add('bar', 0) - process.nextTick(done) + return waitTicks() }) describe('#add()', function () { @@ -160,4 +176,88 @@ describe('Collection', function () { }) }) + describe('deduplicates events', function () { + forEach({ + 'add & update → add': [ + [ + ['add', 'foo', 0], + ['update', 'foo', 1] + ], + { + add: { + foo: 1 + } + } + ], + + 'add & remove → ∅': [ + [ + ['add', 'foo', 0], + ['remove', 'foo'] + ], + {} + ], + + 'update & update → update': [ + [ + ['update', 'bar', 1], + ['update', 'bar', 2] + ], + { + update: { + bar: 2 + } + } + ], + + 'update & remove → remove': [ + [ + ['update', 'bar', 1], + ['remove', 'bar'] + ], + { + remove: { + bar: undefined + } + } + ], + + 'remove & add → update': [ + [ + ['remove', 'bar'], + ['add', 'bar', 0] + ], + { + update: { + bar: 0 + } + } + ] + }, ([operations, results], label) => { + it(label, function () { + const {col} = this + + forEach(operations, ([method, ...args]) => { + col[method](...args) + }) + + const spies = Object.create(null) + forEach(['add', 'update', 'remove'], event => { + col.on(event, (spies[event] = sinon.spy())) + }) + + return waitTicks(2).then(() => { + forEach(spies, (spy, event) => { + const items = results[event] + if (items) { + sinon.assert.calledOnce(spy) + expect(spy.args[0][0]).to.eql(items) + } else { + sinon.assert.notCalled(spy) + } + }) + }) + }) + }) + }) }) From 4ecfa0477d7c37e34d9cab9aa56ae800a8fa5487 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 14:30:16 +0200 Subject: [PATCH 028/103] Optimize Collection#_touch(). --- packages/xo-collection/src/index.js | 31 ++++++++++++----------------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 49e5dd804..f7ce7e225 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -68,24 +68,19 @@ export default class Collection extends EventEmitter { process.nextTick(flush) } - switch (action) { - case 'add': - this._buffer[key] = this._buffer[key] ? 'update' : 'add' - break - case 'remove': - switch (this._buffer[key]) { - case undefined: - case 'update': - this._buffer[key] = 'remove' - break - case 'add': - delete this._buffer[key] - break - } - break - case 'update': - this._buffer[key] = this._buffer[key] || 'update' - break + + if (action === 'add') { + this._buffer[key] = this._buffer[key] ? 'update' : 'add' + } else if (action === 'remove') { + if (this._buffer[key] === 'add') { + delete this._buffer[key] + } else { + this._buffer[key] = 'remove' + } + } else { // update + if (!this._buffer[key]) { + this._buffer[key] = 'update' + } } } From ab221a465be185dca9b457ae3eaf938b400e4b5c Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 16:32:46 +0200 Subject: [PATCH 029/103] Use lodash.foreach instead of native implementation. --- packages/xo-collection/package.json | 2 +- packages/xo-collection/src/index.js | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index c80b2adb9..a677e4c4c 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -22,6 +22,7 @@ ], "dependencies": { "babel-runtime": "^5", + "lodash.foreach": "^3.0.2", "make-error": "^0.3.0" }, "devDependencies": { @@ -29,7 +30,6 @@ "chai": "*", "dirty-chai": "^1.2.0", "event-to-promise": "^0.3.2", - "lodash.foreach": "^3.0.2", "mocha": "*", "sinon": "^1.14.1", "standard": "*" diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index f7ce7e225..b04b32478 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -1,5 +1,6 @@ -import {EventEmitter} from 'events' +import forEach from 'lodash.foreach' import makeError from 'make-error' +import {EventEmitter} from 'events' export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') export const DuplicateItem = makeError('DuplicateItem') @@ -50,7 +51,7 @@ export default class Collection extends EventEmitter { data[this._buffer[key]][key] = this._items[key] } - ['add', 'update', 'remove'].forEach(action => { + forEach(['add', 'update', 'remove'], action => { const items = data[action] if (isNotEmpty(items)) { @@ -194,11 +195,11 @@ export default class Collection extends EventEmitter { } clear () { - for (let key in this._items) { + forEach(this._items, key => { delete this._items[key] this._size-- this._touch('remove', key) - } + }) return this } From b1c73208c58c818b13308a9d83ea9720dedaeeeb Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 8 Apr 2015 16:33:28 +0200 Subject: [PATCH 030/103] Do not return this. --- packages/xo-collection/src/index.js | 9 --------- 1 file changed, 9 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index b04b32478..b048f3b9f 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -130,8 +130,6 @@ export default class Collection extends EventEmitter { this._items[key] = value this._size++ this._touch('add', key) - - return this } set (keyOrObjectWithId, valueIfKey = null) { @@ -143,8 +141,6 @@ export default class Collection extends EventEmitter { this._size++ } this._touch(action, key) - - return this } get (key, defaultValue) { @@ -166,8 +162,6 @@ export default class Collection extends EventEmitter { this._items[key] = value this._touch('update', key) - - return this } touch (keyOrObjectWithId) { @@ -190,8 +184,6 @@ export default class Collection extends EventEmitter { delete this._items[key] this._size-- this._touch('remove', key) - - return this } clear () { @@ -200,7 +192,6 @@ export default class Collection extends EventEmitter { this._size-- this._touch('remove', key) }) - return this } get size () { From f5191cdd42ae706ef1704940fde976aa7d9b3759 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 10:48:47 +0200 Subject: [PATCH 031/103] Better error classes. --- packages/xo-collection/package.json | 2 +- packages/xo-collection/src/index.js | 50 +++++++++++++++++++++++------ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index a677e4c4c..156ecb5af 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -23,7 +23,7 @@ "dependencies": { "babel-runtime": "^5", "lodash.foreach": "^3.0.2", - "make-error": "^0.3.0" + "make-error": "^1.0.0" }, "devDependencies": { "babel": "^5", diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index b048f3b9f..dc18a07a5 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -1,12 +1,8 @@ import forEach from 'lodash.foreach' -import makeError from 'make-error' +import makeError, {BaseError} from 'make-error' import {EventEmitter} from 'events' -export const BufferAlreadyFlushed = makeError('BufferAlreadyFlushed') -export const DuplicateItem = makeError('DuplicateItem') -export const IllegalAdd = makeError('IllegalAdd') -export const IllegalTouch = makeError('IllegalTouch') -export const NoSuchItem = makeError('NoSuchItem') +// =================================================================== function isNotEmpty (map) { /* eslint no-unused-vars: 0*/ @@ -17,6 +13,40 @@ function isNotEmpty (map) { return false } +// =================================================================== + +export class BufferAlreadyFlushed extends BaseError { + constructor () { + super('buffer flush already requested') + } +} + +export class DuplicateItem extends BaseError { + constructor (key) { + super('there is already a item with the key ' + key) + } +} + +export class IllegalTouch extends BaseError { + constructor (value) { + super('only an object value can be touched (found a ' + typeof value + ')') + } +} + +export class InvalidKey extends BaseError { + constructor (key) { + super('invalid key of type ' + typeof key) + } +} + +export class NoSuchItem extends BaseError { + constructor (key) { + super('there is no item with the key ' + key) + } +} + +// ------------------------------------------------------------------- + export default class Collection extends EventEmitter { constructor () { super() @@ -33,7 +63,7 @@ export default class Collection extends EventEmitter { let called = false return () => { if (called) { - throw new BufferAlreadyFlushed('Buffer flush already requested') + throw new BufferAlreadyFlushed() } called = true @@ -113,13 +143,13 @@ export default class Collection extends EventEmitter { _assertHas (key) { if (!this.has(key)) { - throw new NoSuchItem('No ' + key + ' item') + throw new NoSuchItem(key) } } _assertHasNot (key) { if (this.has(key)) { - throw new DuplicateItem('Attempt to duplicate ' + key + ' item') + throw new DuplicateItem(key) } } @@ -169,7 +199,7 @@ export default class Collection extends EventEmitter { this._assertHas(key) const value = this.get(key) if (typeof value !== 'object' || value === null) { - throw new IllegalTouch('Touching a scalar. Not an object') + throw new IllegalTouch(value) } this._touch('update', key) From 0682cbd554892422367f6afd4f7283f06d35140a Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 10:49:08 +0200 Subject: [PATCH 032/103] Test for Collection#touch(). --- packages/xo-collection/src/index.spec.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index ed7edb385..6f4824b2a 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -176,6 +176,22 @@ describe('Collection', function () { }) }) + describe('touch()', function () { + it('can be used to signal an indirect update', function () { + const foo = { id: 'foo' } + this.col.add(foo) + + return waitTicks().then(() => { + this.col.touch(foo) + + return eventToPromise(this.col, 'update', (items) => { + expect(items).to.have.all.keys('foo') + expect(items.foo).to.equal(foo) + }) + }) + }) + }) + describe('deduplicates events', function () { forEach({ 'add & update → add': [ From bf1d76d85330897f6356db1fdfd2eac0b97bcf44 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 10:49:25 +0200 Subject: [PATCH 033/103] Source map support for tests. --- packages/xo-collection/package.json | 1 + packages/xo-collection/src/index.spec.js | 3 +++ 2 files changed, 4 insertions(+) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 156ecb5af..13f6732b3 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -32,6 +32,7 @@ "event-to-promise": "^0.3.2", "mocha": "*", "sinon": "^1.14.1", + "source-map-support": "*", "standard": "*" }, "scripts": { diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 6f4824b2a..4ef572483 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -10,6 +10,9 @@ import chai, {expect} from 'chai' import dirtyChai from 'dirty-chai' chai.use(dirtyChai) +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() + function waitTicks (n = 1) { const {nextTick} = process From ef2eec4c4a8a824dfa5f73c37fb6e1d81312404b Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 10:50:23 +0200 Subject: [PATCH 034/103] Minor build updates. --- packages/xo-collection/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 13f6732b3..2e96380f4 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -37,9 +37,9 @@ }, "scripts": { "build": "mkdir --parents dist && babel --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", - "dev": "mkdir --parents dist && babel --watch --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", + "dev": "mkdir --parents dist && babel --watch --optional=runtime --source-maps --out-dir=dist/ src/", "prepublish": "npm run build", - "test": "standard && npm run build && mocha 'dist/**/*.spec.js'", + "test": "standard && mocha 'dist/**/*.spec.js'", "test-dev": "standard && mocha --watch --reporter=min 'dist/**/*.spec.js'" }, "standard": { From 964e461597ff489162368ebd73fac64ae76a545e Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 10:51:01 +0200 Subject: [PATCH 035/103] Better Collection#_resolveItem(). --- packages/xo-collection/src/index.js | 45 +++++++++++++++++------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index dc18a07a5..2f21f3d00 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -123,22 +123,31 @@ export default class Collection extends EventEmitter { return Object.hasOwnProperty.call(this._items, key) } - _resolveItem (keyOrObjectWithId, valueIfKey = null) { - let value - let key = this.getId(keyOrObjectWithId) + _isValidKey (key) { + return typeof key === 'number' || typeof key === 'string' + } - if (undefined === key) { - if (arguments.length < 2) { - throw new IllegalAdd('Missing value, or object value does not provide id/key') - } else { - key = keyOrObjectWithId - value = valueIfKey - } - } else { - value = keyOrObjectWithId + _assertValidKey (key) { + if (!this._isValidKey(key)) { + throw new InvalidKey(key) + } + } + + _resolveItem (keyOrObjectWithId, valueIfKey = undefined) { + if (valueIfKey !== undefined) { + this._assertValidKey(keyOrObjectWithId) + + return [keyOrObjectWithId, valueIfKey] } - return [key, value] + if (this._isValidKey(keyOrObjectWithId)) { + return [keyOrObjectWithId] + } + + const key = this.getId(keyOrObjectWithId) + this._assertValidKey(key) + + return [key, keyOrObjectWithId] } _assertHas (key) { @@ -153,7 +162,7 @@ export default class Collection extends EventEmitter { } } - add (keyOrObjectWithId, valueIfKey = null) { + add (keyOrObjectWithId, valueIfKey = undefined) { const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) this._assertHasNot(key) @@ -162,7 +171,7 @@ export default class Collection extends EventEmitter { this._touch('add', key) } - set (keyOrObjectWithId, valueIfKey = null) { + set (keyOrObjectWithId, valueIfKey = undefined) { const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) const action = this.has(key) ? 'update' : 'add' @@ -186,7 +195,7 @@ export default class Collection extends EventEmitter { this._assertHas(key) } - update (keyOrObjectWithId, valueIfKey = null) { + update (keyOrObjectWithId, valueIfKey = undefined) { const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) this._assertHas(key) @@ -195,7 +204,7 @@ export default class Collection extends EventEmitter { } touch (keyOrObjectWithId) { - const [key] = this._resolveItem(keyOrObjectWithId, null) + const [key] = this._resolveItem(keyOrObjectWithId) this._assertHas(key) const value = this.get(key) if (typeof value !== 'object' || value === null) { @@ -208,7 +217,7 @@ export default class Collection extends EventEmitter { } remove (keyOrObjectWithId) { - const [key] = this._resolveItem(keyOrObjectWithId, null) + const [key] = this._resolveItem(keyOrObjectWithId) this._assertHas(key) delete this._items[key] From 41dfbc2709d775f1b171cb5eb035ebe09a59eba1 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 11:41:02 +0200 Subject: [PATCH 036/103] Publish to npm as xo-collection. --- packages/xo-collection/package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 2e96380f4..4e2f6a7b2 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,5 @@ { - "private": true, - "name": "collection", + "name": "xo-collection", "version": "0.0.0", "license": "ISC", "description": "Generic in-memory collection with events", From e072ff2d778843058ab92f20cc0ee9f67683171e Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 10 Apr 2015 11:51:54 +0200 Subject: [PATCH 037/103] Update README.md --- packages/xo-collection/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index c49b2f59e..2f35e8645 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -4,16 +4,16 @@ ## Install -Installation of the [npm package](https://npmjs.org/package/collection): +Installation of the [npm package](https://npmjs.org/package/xo-collection): ``` -> npm install --save collection +> npm install --save xo-collection ``` ## Usage ```javascript -var Collection = require('collection') +var Collection = require('xo-collection') ``` ### Creation From 34ac4b25afe092a1073f80db5d98a7ca5e45f508 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 13 Apr 2015 14:53:25 +0200 Subject: [PATCH 038/103] Test and fix #clear(). --- packages/xo-collection/src/index.js | 2 +- packages/xo-collection/src/index.spec.js | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 2f21f3d00..9fdf2f81e 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -226,7 +226,7 @@ export default class Collection extends EventEmitter { } clear () { - forEach(this._items, key => { + forEach(this._items, (_, key) => { delete this._items[key] this._size-- this._touch('remove', key) diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 4ef572483..a119a171f 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -195,6 +195,19 @@ describe('Collection', function () { }) }) + describe('clear()', function () { + it('removes all items from the collection', function () { + this.col.clear() + + expect(this.col.size).to.equal(0) + + return eventToPromise(this.col, 'remove').then((items) => { + expect(items).to.have.all.keys('bar') + expect(items.bar).to.not.exist() + }) + }) + }) + describe('deduplicates events', function () { forEach({ 'add & update → add': [ From 653a9526f5802acec3fdb962dcd1c917391a5f33 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 13 Apr 2015 14:54:19 +0200 Subject: [PATCH 039/103] 0.0.1 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 4e2f6a7b2..e26e98785 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.0.0", + "version": "0.0.1", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From 783ab0b6111f127aa1b15f4f6e891bd35ed7013d Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 13 Apr 2015 20:23:43 +0200 Subject: [PATCH 040/103] Initial view implementation (fix #3). --- packages/xo-collection/package.json | 2 + packages/xo-collection/src/view.example.js | 40 +++++++++++ packages/xo-collection/src/view.js | 78 ++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 packages/xo-collection/src/view.example.js create mode 100644 packages/xo-collection/src/view.js diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index e26e98785..ebe452ed7 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -21,6 +21,8 @@ ], "dependencies": { "babel-runtime": "^5", + "lodash.bind": "^3.1.0", + "lodash.callback": "^3.1.1", "lodash.foreach": "^3.0.2", "make-error": "^1.0.0" }, diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js new file mode 100644 index 000000000..ddc8e8b92 --- /dev/null +++ b/packages/xo-collection/src/view.example.js @@ -0,0 +1,40 @@ +import Collection from './' +import View from './view' + +const users = new Collection() +users.getId = (user) => user.name + +const activeUsers = new View(users, 'active') +activeUsers.on('add', console.log) +activeUsers.on('update', console.log) +activeUsers.on('remove', console.log) + +users.add({ + name: 'bob' +}) + +users.add({ + name: 'clara', + active: true +}) + +users.add({ + name: 'ophelia' +}) + +users.add({ + name: 'Steve', + active: true +}) + +setTimeout(function () { + console.log('-----') + + users.set({ + name: 'ophelia', + active: true + }) + users.set({ + name: 'Steve' + }) +}, 10) diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js new file mode 100644 index 000000000..22a4935f3 --- /dev/null +++ b/packages/xo-collection/src/view.js @@ -0,0 +1,78 @@ +import bind from 'lodash.bind' +import createCallback from 'lodash.callback' +import forEach from 'lodash.foreach' + +import Collection from './' + +// =================================================================== + +export default class View extends Collection { + constructor (collection, predicate, thisArg) { + super() + + this._collection = collection + this._predicate = createCallback(predicate, thisArg) + + // Bound versions of listeners. + this._onAdd = bind(this._onAdd, this) + this._onUpdate = bind(this._onUpdate, this) + this._onRemove = bind(this._onRemove, this) + + // Register listeners. + this._collection.on('add', this._onAdd) + this._collection.on('update', this._onUpdate) + this._collection.on('remove', this._onRemove) + } + + destroy () { + this._collection.removeListener('add', this._onAdd) + this._collection.removeListener('update', this._onUpdate) + this._collection.removeListener('remove', this._onRemove) + } + + add () { + throw new Error('a view is read only') + } + + clear () { + throw new Error('a view is read only') + } + + set () { + throw new Error('a view is read only') + } + + update () { + throw new Error('a view is read only') + } + + _onAdd (items) { + const {_predicate: predicate} = this + + forEach(items, (value, key) => { + if (predicate(value, key, this)) { + super.add(key, value) + } + }) + } + + _onUpdate (items) { + const {_predicate: predicate} = this + + forEach(items, (value, key) => { + if (predicate(value, key, this)) { + super.set(key, value) + } else if (super.has(key)) { + super.remove(key) + } + }) + } + + _onRemove (items) { + forEach(items, (value, key) => { + if (super.has(key)) { + super.remove(key) + } + }) + } +} From bd3954a5f134bc3f51bbd766af14b28d97d6b2eb Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 14 Apr 2015 10:47:47 +0200 Subject: [PATCH 041/103] Rename index.* to collection.*. --- packages/xo-collection/.npmignore | 2 ++ packages/xo-collection/package.json | 2 +- packages/xo-collection/src/{index.js => collection.js} | 0 .../xo-collection/src/{index.spec.js => collection.spec.js} | 2 +- packages/xo-collection/src/view.example.js | 2 +- packages/xo-collection/src/view.js | 2 +- 6 files changed, 6 insertions(+), 4 deletions(-) rename packages/xo-collection/src/{index.js => collection.js} (100%) rename packages/xo-collection/src/{index.spec.js => collection.spec.js} (99%) diff --git a/packages/xo-collection/.npmignore b/packages/xo-collection/.npmignore index 5f4b80cec..815f54c57 100644 --- a/packages/xo-collection/.npmignore +++ b/packages/xo-collection/.npmignore @@ -1,2 +1,4 @@ +*.example.js +*.example.js.map *.spec.js *.spec.js.map diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index ebe452ed7..58cbdf4ba 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -15,7 +15,7 @@ "email": "fabrice.marsaud@vates.fr" }, "preferGlobal": false, - "main": "dist/", + "main": "dist/collection", "files": [ "dist/" ], diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/collection.js similarity index 100% rename from packages/xo-collection/src/index.js rename to packages/xo-collection/src/collection.js diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/collection.spec.js similarity index 99% rename from packages/xo-collection/src/index.spec.js rename to packages/xo-collection/src/collection.spec.js index a119a171f..d5d9b7207 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import Collection, {DuplicateItem, NoSuchItem} from './index' +import Collection, {DuplicateItem, NoSuchItem} from './collection' import eventToPromise from 'event-to-promise' import forEach from 'lodash.foreach' diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js index ddc8e8b92..29768d51d 100644 --- a/packages/xo-collection/src/view.example.js +++ b/packages/xo-collection/src/view.example.js @@ -1,4 +1,4 @@ -import Collection from './' +import Collection from './collection' import View from './view' const users = new Collection() diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index 22a4935f3..a0ee74d69 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -2,7 +2,7 @@ import bind from 'lodash.bind' import createCallback from 'lodash.callback' import forEach from 'lodash.foreach' -import Collection from './' +import Collection from './collection' // =================================================================== From 51f4578a417198fd6a0e72995b724f5bc5048ad0 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 14 Apr 2015 10:58:58 +0200 Subject: [PATCH 042/103] View handles existing items. --- packages/xo-collection/src/view.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index a0ee74d69..358fe74cb 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -13,6 +13,9 @@ export default class View extends Collection { this._collection = collection this._predicate = createCallback(predicate, thisArg) + // Handles initial items. + this._onAdd(this._collection.all) + // Bound versions of listeners. this._onAdd = bind(this._onAdd, this) this._onUpdate = bind(this._onUpdate, this) @@ -24,6 +27,8 @@ export default class View extends Collection { this._collection.on('remove', this._onRemove) } + // This method is necessary to free the memory of the view if its + // life span is shorter than the collection. destroy () { this._collection.removeListener('add', this._onAdd) this._collection.removeListener('update', this._onUpdate) @@ -51,7 +56,10 @@ export default class View extends Collection { forEach(items, (value, key) => { if (predicate(value, key, this)) { - super.add(key, value) + // super.add() cannot be used because the item may already be + // in the view if it was already present at the creation of + // the view and its event not already emitted. + super.set(key, value) } }) } From 1f30a1956606258aa7651dac59989ce658aa6552 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 14 Apr 2015 10:59:08 +0200 Subject: [PATCH 043/103] Improved view example. --- packages/xo-collection/src/view.example.js | 32 ++++++++++++++++------ 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js index 29768d51d..136e0c70b 100644 --- a/packages/xo-collection/src/view.example.js +++ b/packages/xo-collection/src/view.example.js @@ -1,32 +1,48 @@ +import forEach from 'lodash.foreach' + import Collection from './collection' import View from './view' +// =================================================================== + +// Create the collection. const users = new Collection() users.getId = (user) => user.name -const activeUsers = new View(users, 'active') -activeUsers.on('add', console.log) -activeUsers.on('update', console.log) -activeUsers.on('remove', console.log) - +// Inserts some data. users.add({ name: 'bob' }) - users.add({ name: 'clara', active: true }) - users.add({ name: 'ophelia' }) - users.add({ name: 'Steve', active: true }) +// ------------------------------------------------------------------- + +// Create the view. +const activeUsers = new View(users, 'active') + +// Register some event listeners to see the changes. +activeUsers.on('add', users => { + forEach(users, (_, id) => { + console.log('+ active user:', id) + }) +}) +activeUsers.on('remove', users => { + forEach(users, (_, id) => { + console.log('- active user:', id) + }) +}) + +// Make some changes in the future. setTimeout(function () { console.log('-----') From e004ba63f8a988cc1353c431ceced1880305875a Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 15 Apr 2015 10:46:06 +0200 Subject: [PATCH 044/103] Remove unused JSHint conf. --- packages/xo-collection/.jshintrc | 93 -------------------------------- 1 file changed, 93 deletions(-) delete mode 100644 packages/xo-collection/.jshintrc diff --git a/packages/xo-collection/.jshintrc b/packages/xo-collection/.jshintrc deleted file mode 100644 index 9e30c8a86..000000000 --- a/packages/xo-collection/.jshintrc +++ /dev/null @@ -1,93 +0,0 @@ -{ - // Julien Fontanet JSHint configuration - // https://gist.github.com/julien-f/8095615 - // - // Changes from defaults: - // - all enforcing options (except `++` & `--`) enabled - // - single quotes - // - indentation set to 2 instead of 4 - // - almost all relaxing options disabled - // - environments are set to Node.js - // - // See http://jshint.com/docs/ for more details - - "maxerr" : 50, // {int} Maximum error before stopping - - // Enforcing - "bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.) - "camelcase" : true, // true: Identifiers must be in camelCase - "curly" : true, // true: Require {} for every new block or scope - "eqeqeq" : true, // true: Require triple equals (===) for comparison - "forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty() - "freeze" : true, // true: Prohibit overwriting prototypes of native objects (Array, Date, ...) - "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` - "indent" : 2, // {int} Number of spaces to use for indentation - "latedef" : true, // true: Require variables/functions to be defined before being used - "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` - "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` - "noempty" : true, // true: Prohibit use of empty blocks - "nonbsp" : true, // true: Prohibit use of non breakable spaces - "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment) - "plusplus" : false, // true: Prohibit use of `++` & `--` - "quotmark" : "single", // Quotation mark consistency: - // false : do nothing (default) - // true : ensure whatever is used is consistent - // "single" : require single quotes - // "double" : require double quotes - "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) - "unused" : true, // true: Require all defined variables be used - "strict" : false, // true: Requires all functions run in ES5 Strict Mode - "maxcomplexity" : 7, // {int} Max cyclomatic complexity per function - "maxdepth" : 3, // {int} Max depth of nested blocks (within functions) - "maxlen" : 80, // {int} Max number of characters per line - "maxparams" : 4, // {int} Max number of formal params allowed per function - "maxstatements" : 20, // {int} Max number statements per function - - // Relaxing - "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) - "boss" : false, // true: Tolerate assignments where comparisons would be expected - "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. - "eqnull" : false, // true: Tolerate use of `== null` - "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`) - "evil" : false, // true: Tolerate use of `eval` and `new Function()` - "expr" : false, // true: Tolerate `ExpressionStatement` as Programs - "funcscope" : false, // true: Tolerate defining variables inside control statements - "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') - "iterator" : false, // true: Tolerate using the `__iterator__` property - "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block - "laxbreak" : false, // true: Tolerate possibly unsafe line breakings - "laxcomma" : false, // true: Tolerate comma-first style coding - "loopfunc" : false, // true: Tolerate functions being defined in loops - "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) - // (ex: `for each`, multiple try/catch, function expression…) - "multistr" : false, // true: Tolerate multi-line strings - "notypeof" : false, // true: Tolerate typeof comparison with unknown values. - "proto" : false, // true: Tolerate using the `__proto__` property - "scripturl" : false, // true: Tolerate script-targeted URLs - "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` - "sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation - "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` - "validthis" : false, // true: Tolerate using this in a non-constructor function - "noyield" : false, // true: Tolerate generators without yields - - // Environments - "browser" : false, // Web Browser (window, document, etc) - "browserify" : false, // Browserify (node.js code in the browser) - "couch" : false, // CouchDB - "devel" : false, // Development/debugging (alert, confirm, etc) - "dojo" : false, // Dojo Toolkit - "jquery" : false, // jQuery - "mocha" : false, // mocha - "mootools" : false, // MooTools - "node" : true, // Node.js - "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) - "phantom" : false, // PhantomJS - "prototypejs" : false, // Prototype and Scriptaculous - "rhino" : false, // Rhino - "worker" : false, // Web Workers - "wsh" : false, // Windows Scripting Host - "yui" : false, // Yahoo User Interface - - // Custom Globals - "globals" : {} // additional predefined global variables -} From 7941a24d5127914f3e6dcca9ec40f16561d65ac9 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 15 Apr 2015 15:16:28 +0200 Subject: [PATCH 045/103] Force npm test to be successful before committing. --- packages/xo-collection/package.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 58cbdf4ba..677f01f1b 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -31,6 +31,7 @@ "chai": "*", "dirty-chai": "^1.2.0", "event-to-promise": "^0.3.2", + "ghooks": "^0.3.2", "mocha": "*", "sinon": "^1.14.1", "source-map-support": "*", @@ -47,5 +48,10 @@ "ignore": [ "dist/**" ] + }, + "config": { + "ghooks": { + "pre-commit": "npm test" + } } } From fcea7fd4bf1973e4e099f5862ad95ff49cad23db Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sat, 18 Apr 2015 19:37:04 +0200 Subject: [PATCH 046/103] `mkdir -p` is more portable. --- packages/xo-collection/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 677f01f1b..35a59588c 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -38,8 +38,8 @@ "standard": "*" }, "scripts": { - "build": "mkdir --parents dist && babel --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", - "dev": "mkdir --parents dist && babel --watch --optional=runtime --source-maps --out-dir=dist/ src/", + "build": "mkdir -p dist && babel --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", + "dev": "mkdir -p dist && babel --watch --optional=runtime --source-maps --out-dir=dist/ src/", "prepublish": "npm run build", "test": "standard && mocha 'dist/**/*.spec.js'", "test-dev": "standard && mocha --watch --reporter=min 'dist/**/*.spec.js'" From 5b020035d60d87d5c82b5927355198f24b727590 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sat, 18 Apr 2015 21:34:36 +0200 Subject: [PATCH 047/103] Collection is iterable. --- packages/xo-collection/src/collection.js | 8 ++++++++ packages/xo-collection/src/collection.spec.js | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 9fdf2f81e..19eda32d4 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -240,4 +240,12 @@ export default class Collection extends EventEmitter { get all () { return this._items } + + * [Symbol.iterator] () { + const {_items: items} = this + + for (let key in items) { + yield items[key] + } + } } diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index d5d9b7207..03f36d153 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -36,6 +36,13 @@ describe('Collection', function () { return waitTicks() }) + it('is iterable', function () { + const iterator = this.col[Symbol.iterator]() + + expect(iterator.next()).to.eql({done: false, value: 0}) + expect(iterator.next()).to.eql({done: true, value: undefined}) + }) + describe('#add()', function () { it('adds item to the collection', function () { const spy = sinon.spy() From 7024b5ec1b135394477aa565bb9b8b8f31860c47 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sat, 18 Apr 2015 21:58:17 +0200 Subject: [PATCH 048/103] Reorganization of Collection code. --- packages/xo-collection/src/collection.js | 290 ++++++++++++----------- 1 file changed, 156 insertions(+), 134 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 19eda32d4..7aff7bbb9 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -57,6 +57,121 @@ export default class Collection extends EventEmitter { this._size = 0 } + getId (item) { + return item && item.id + } + + // ----------------------------------------------------------------- + // Properties + // ----------------------------------------------------------------- + + get all () { + return this._items + } + + get size () { + return this._size + } + + // ----------------------------------------------------------------- + // Manipulation + // ----------------------------------------------------------------- + + add (keyOrObjectWithId, valueIfKey = undefined) { + const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) + this._assertHasNot(key) + + this._items[key] = value + this._size++ + this._touch('add', key) + } + + clear () { + forEach(this._items, (_, key) => { + delete this._items[key] + this._size-- + this._touch('remove', key) + }) + } + + remove (keyOrObjectWithId) { + const [key] = this._resolveItem(keyOrObjectWithId) + this._assertHas(key) + + delete this._items[key] + this._size-- + this._touch('remove', key) + } + + set (keyOrObjectWithId, valueIfKey = undefined) { + const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) + + const action = this.has(key) ? 'update' : 'add' + this._items[key] = value + if (action === 'add') { + this._size++ + } + this._touch(action, key) + } + + touch (keyOrObjectWithId) { + const [key] = this._resolveItem(keyOrObjectWithId) + this._assertHas(key) + const value = this.get(key) + if (typeof value !== 'object' || value === null) { + throw new IllegalTouch(value) + } + + this._touch('update', key) + + return this.get(key) + } + + update (keyOrObjectWithId, valueIfKey = undefined) { + const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) + this._assertHas(key) + + this._items[key] = value + this._touch('update', key) + } + + // ----------------------------------------------------------------- + // Query + // ----------------------------------------------------------------- + + get (key, defaultValue) { + if (this.has(key)) { + return this._items[key] + } + + if (arguments.length > 1) { + return defaultValue + } + + // Throws a NoSuchItem. + this._assertHas(key) + } + + has (key) { + return Object.hasOwnProperty.call(this._items, key) + } + + // ----------------------------------------------------------------- + // Iteration + // ----------------------------------------------------------------- + + * [Symbol.iterator] () { + const {_items: items} = this + + for (let key in items) { + yield items[key] + } + } + + // ----------------------------------------------------------------- + // Events buffering + // ----------------------------------------------------------------- + bufferEvents () { ++this._buffering @@ -93,6 +208,47 @@ export default class Collection extends EventEmitter { } } + // ================================================================= + + _assertHas (key) { + if (!this.has(key)) { + throw new NoSuchItem(key) + } + } + + _assertHasNot (key) { + if (this.has(key)) { + throw new DuplicateItem(key) + } + } + + _assertValidKey (key) { + if (!this._isValidKey(key)) { + throw new InvalidKey(key) + } + } + + _isValidKey (key) { + return typeof key === 'number' || typeof key === 'string' + } + + _resolveItem (keyOrObjectWithId, valueIfKey = undefined) { + if (valueIfKey !== undefined) { + this._assertValidKey(keyOrObjectWithId) + + return [keyOrObjectWithId, valueIfKey] + } + + if (this._isValidKey(keyOrObjectWithId)) { + return [keyOrObjectWithId] + } + + const key = this.getId(keyOrObjectWithId) + this._assertValidKey(key) + + return [key, keyOrObjectWithId] + } + _touch (action, key) { if (this._buffering === 0) { const flush = this.bufferEvents() @@ -114,138 +270,4 @@ export default class Collection extends EventEmitter { } } } - - getId (item) { - return item && item.id - } - - has (key) { - return Object.hasOwnProperty.call(this._items, key) - } - - _isValidKey (key) { - return typeof key === 'number' || typeof key === 'string' - } - - _assertValidKey (key) { - if (!this._isValidKey(key)) { - throw new InvalidKey(key) - } - } - - _resolveItem (keyOrObjectWithId, valueIfKey = undefined) { - if (valueIfKey !== undefined) { - this._assertValidKey(keyOrObjectWithId) - - return [keyOrObjectWithId, valueIfKey] - } - - if (this._isValidKey(keyOrObjectWithId)) { - return [keyOrObjectWithId] - } - - const key = this.getId(keyOrObjectWithId) - this._assertValidKey(key) - - return [key, keyOrObjectWithId] - } - - _assertHas (key) { - if (!this.has(key)) { - throw new NoSuchItem(key) - } - } - - _assertHasNot (key) { - if (this.has(key)) { - throw new DuplicateItem(key) - } - } - - add (keyOrObjectWithId, valueIfKey = undefined) { - const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) - this._assertHasNot(key) - - this._items[key] = value - this._size++ - this._touch('add', key) - } - - set (keyOrObjectWithId, valueIfKey = undefined) { - const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) - - const action = this.has(key) ? 'update' : 'add' - this._items[key] = value - if (action === 'add') { - this._size++ - } - this._touch(action, key) - } - - get (key, defaultValue) { - if (this.has(key)) { - return this._items[key] - } - - if (arguments.length > 1) { - return defaultValue - } - - // Throws a NoSuchItem. - this._assertHas(key) - } - - update (keyOrObjectWithId, valueIfKey = undefined) { - const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) - this._assertHas(key) - - this._items[key] = value - this._touch('update', key) - } - - touch (keyOrObjectWithId) { - const [key] = this._resolveItem(keyOrObjectWithId) - this._assertHas(key) - const value = this.get(key) - if (typeof value !== 'object' || value === null) { - throw new IllegalTouch(value) - } - - this._touch('update', key) - - return this.get(key) - } - - remove (keyOrObjectWithId) { - const [key] = this._resolveItem(keyOrObjectWithId) - this._assertHas(key) - - delete this._items[key] - this._size-- - this._touch('remove', key) - } - - clear () { - forEach(this._items, (_, key) => { - delete this._items[key] - this._size-- - this._touch('remove', key) - }) - } - - get size () { - return this._size - } - - get all () { - return this._items - } - - * [Symbol.iterator] () { - const {_items: items} = this - - for (let key in items) { - yield items[key] - } - } } From 160522c52020da73faf64564de904b8da242379c Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sat, 18 Apr 2015 22:04:37 +0200 Subject: [PATCH 049/103] Collection iteration more similar to Map. --- packages/xo-collection/src/collection.js | 16 ++++++++++++++++ packages/xo-collection/src/collection.spec.js | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 7aff7bbb9..77e997d32 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -163,6 +163,22 @@ export default class Collection extends EventEmitter { * [Symbol.iterator] () { const {_items: items} = this + for (let key in items) { + yield [key, items[key]] + } + } + + * keys () { + const {_items: items} = this + + for (let key in items) { + yield key + } + } + + * values () { + const {_items: items} = this + for (let key in items) { yield items[key] } diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 03f36d153..80ff2a3dc 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -39,8 +39,26 @@ describe('Collection', function () { it('is iterable', function () { const iterator = this.col[Symbol.iterator]() + expect(iterator.next()).to.eql({done: false, value: ['bar', 0]}) + expect(iterator.next()).to.eql({done: true, value: undefined}) + }) + + describe('#keys()', function () { + it('returns an iterator over the keys', function () { + const iterator = this.col.keys() + + expect(iterator.next()).to.eql({done: false, value: 'bar'}) + expect(iterator.next()).to.eql({done: true, value: undefined}) + }) + }) + + describe('#values()', function () { + it('returns an iterator over the values', function () { + const iterator = this.col.values() + expect(iterator.next()).to.eql({done: false, value: 0}) expect(iterator.next()).to.eql({done: true, value: undefined}) + }) }) describe('#add()', function () { From d4d8ea6cf2b335fa4b74dbd84e21446c58e41c01 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sat, 18 Apr 2015 22:20:57 +0200 Subject: [PATCH 050/103] Collection #getId() renamed to getKey(). --- packages/xo-collection/src/collection.js | 4 ++-- packages/xo-collection/src/view.example.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 77e997d32..0c535eeae 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -57,7 +57,7 @@ export default class Collection extends EventEmitter { this._size = 0 } - getId (item) { + getKey (item) { return item && item.id } @@ -259,7 +259,7 @@ export default class Collection extends EventEmitter { return [keyOrObjectWithId] } - const key = this.getId(keyOrObjectWithId) + const key = this.getKey(keyOrObjectWithId) this._assertValidKey(key) return [key, keyOrObjectWithId] diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js index 136e0c70b..ef6e17b7a 100644 --- a/packages/xo-collection/src/view.example.js +++ b/packages/xo-collection/src/view.example.js @@ -7,7 +7,7 @@ import View from './view' // Create the collection. const users = new Collection() -users.getId = (user) => user.name +users.getKey = (user) => user.name // Inserts some data. users.add({ From 1269411771fb2bba2067e13e05e47bff144a118a Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sat, 18 Apr 2015 22:33:32 +0200 Subject: [PATCH 051/103] Add iteration to the README. --- packages/xo-collection/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 2f35e8645..f6367957c 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -163,6 +163,22 @@ col.on('remove', (removed) => { }) ``` +### Iteration + +```javascript +for (let [key, value] of col) { + console.log('- %s: %j', key, value) +} + +for (let key of col.keys()) { + console.log('- %s', key) +} + +for (let value of col.values()) { + console.log('- %j', value) +} +``` + ## Development ### Installing dependencies From 00f944f3f473d2dd11df2e9fb66fb348ce23353a Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sun, 19 Apr 2015 00:42:02 +0200 Subject: [PATCH 052/103] Remove unused import. --- packages/xo-collection/src/collection.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 0c535eeae..16a574c7b 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -1,5 +1,5 @@ import forEach from 'lodash.foreach' -import makeError, {BaseError} from 'make-error' +import {BaseError} from 'make-error' import {EventEmitter} from 'events' // =================================================================== From 3da2a618b9166d92afff29b7dbe67cd34b357835 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 27 Apr 2015 10:55:22 +0200 Subject: [PATCH 053/103] Coding style. --- packages/xo-collection/src/collection.spec.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 80ff2a3dc..883010824 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -45,19 +45,19 @@ describe('Collection', function () { describe('#keys()', function () { it('returns an iterator over the keys', function () { - const iterator = this.col.keys() + const iterator = this.col.keys() - expect(iterator.next()).to.eql({done: false, value: 'bar'}) - expect(iterator.next()).to.eql({done: true, value: undefined}) + expect(iterator.next()).to.eql({done: false, value: 'bar'}) + expect(iterator.next()).to.eql({done: true, value: undefined}) }) }) describe('#values()', function () { it('returns an iterator over the values', function () { - const iterator = this.col.values() + const iterator = this.col.values() - expect(iterator.next()).to.eql({done: false, value: 0}) - expect(iterator.next()).to.eql({done: true, value: undefined}) + expect(iterator.next()).to.eql({done: false, value: 0}) + expect(iterator.next()).to.eql({done: true, value: undefined}) }) }) From d78522f5e1e8523fae993c7d8648e0ea188dd1b0 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 27 Apr 2015 12:14:30 +0200 Subject: [PATCH 054/103] Comment doc for Collection#getId(). --- packages/xo-collection/src/collection.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 16a574c7b..dc82f006a 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -57,8 +57,12 @@ export default class Collection extends EventEmitter { this._size = 0 } - getKey (item) { - return item && item.id + // Overridable method used to compute the key of an item when + // unspecified. + // + // Default implementation returns the `id` property. + getKey (value) { + return value && value.id } // ----------------------------------------------------------------- From e6e8ccc85585ed3b981aaf9d3cf43a028b0400e2 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 27 Apr 2015 14:57:50 +0200 Subject: [PATCH 055/103] Remove standard from `npm test`. Currently broken du to due to eslint/espree#123 --- packages/xo-collection/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 35a59588c..b81e3778a 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -41,8 +41,8 @@ "build": "mkdir -p dist && babel --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", "dev": "mkdir -p dist && babel --watch --optional=runtime --source-maps --out-dir=dist/ src/", "prepublish": "npm run build", - "test": "standard && mocha 'dist/**/*.spec.js'", - "test-dev": "standard && mocha --watch --reporter=min 'dist/**/*.spec.js'" + "test": "mocha 'dist/**/*.spec.js'", + "test-dev": "mocha --watch --reporter=min 'dist/**/*.spec.js'" }, "standard": { "ignore": [ From 22caa0ee6669a57afe6ded31af855ffa0ca8ff53 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 27 Apr 2015 15:00:18 +0200 Subject: [PATCH 056/103] Initial Index implementation (see #1). --- packages/xo-collection/src/collection.js | 50 ++++++- packages/xo-collection/src/index.js | 157 +++++++++++++++++++++ packages/xo-collection/src/index.spec.js | 165 +++++++++++++++++++++++ 3 files changed, 371 insertions(+), 1 deletion(-) create mode 100644 packages/xo-collection/src/index.js create mode 100644 packages/xo-collection/src/index.spec.js diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index dc82f006a..c5f66eb1e 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -13,6 +13,8 @@ function isNotEmpty (map) { return false } +const {hasOwnProperty} = Object + // =================================================================== export class BufferAlreadyFlushed extends BaseError { @@ -21,6 +23,12 @@ export class BufferAlreadyFlushed extends BaseError { } } +export class DuplicateIndex extends BaseError { + constructor (name) { + super('there is already an index with the name ' + name) + } +} + export class DuplicateItem extends BaseError { constructor (key) { super('there is already a item with the key ' + key) @@ -39,6 +47,12 @@ export class InvalidKey extends BaseError { } } +export class NoSuchIndex extends BaseError { + constructor (key) { + super('there is no index with the name ' + name) + } +} + export class NoSuchItem extends BaseError { constructor (key) { super('there is no item with the key ' + key) @@ -53,6 +67,8 @@ export default class Collection extends EventEmitter { this._buffer = Object.create(null) this._buffering = 0 + this._indexes = Object.create(null) + this._indexedItems = Object.create(null) this._items = Object.create(null) this._size = 0 } @@ -73,6 +89,10 @@ export default class Collection extends EventEmitter { return this._items } + get indexes () { + return this._indexedItems + } + get size () { return this._size } @@ -157,7 +177,35 @@ export default class Collection extends EventEmitter { } has (key) { - return Object.hasOwnProperty.call(this._items, key) + return hasOwnProperty.call(this._items, key) + } + + // ----------------------------------------------------------------- + // Indexes + // ----------------------------------------------------------------- + + createIndex (name, index) { + index._attachCollection(this) + + const {_indexes: indexes} = this + if (hasOwnProperty.call(indexes, name)) { + throw new DuplicateIndex(name) + } + indexes[name] = index + this._indexedItems[name] = index.itemsByHash + } + + deleteIndex (name) { + const {_indexes: indexes} = this + if (!hasOwnProperty.call(indexes, name)) { + throw new NoSuchIndex(name) + } + + const index = indexes[name] + delete indexes[name] + delete this._indexedItems[name] + + index._detachCollection() } // ----------------------------------------------------------------- diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js new file mode 100644 index 000000000..a4741d557 --- /dev/null +++ b/packages/xo-collection/src/index.js @@ -0,0 +1,157 @@ +import bind from 'lodash.bind' +import {BaseError} from 'make-error' + +// =================================================================== + +class NotImplemented extends BaseError { + constructor (message) { + super(message || 'this method is not implemented') + } +} + +// =================================================================== + +const clearObject = (object) => { + for (let key in object) { + delete object[key] + } +} + +const isEmpty = (object) => { + /* eslint no-unused-vars: 0 */ + for (let key in object) { + return false + } + return true +} + +// =================================================================== + +export default class Index { + constructor () { + this._itemsByHash = Object.create(null) + this._keysToHash = Object.create(null) + + // Bound versions of listeners. + this._onAdd = bind(this._onAdd, this) + this._onUpdate = bind(this._onUpdate, this) + this._onRemove = bind(this._onRemove, this) + } + + // This method is used to compute the hash under which an item must + // be saved. + computeHash (value, key) { + throw new NotImplemented('this method must be overridden') + } + + // Remove empty items lists. + sweep () { + const {_itemsByHash: itemsByHash} = this + for (let hash in itemsByHash) { + if (isEmpty(itemsByHash[hash])) { + delete itemsByHash[hash] + } + } + } + + // ----------------------------------------------------------------- + + get itemsByHash () { + return this._itemsByHash + } + + // ----------------------------------------------------------------- + + _attachCollection (collection) { + // Add existing entries. + // + // FIXME: I think there may be a race condition if the `add` event + // has not been emitted yet. + this._onAdd(collection.all) + + collection.on('add', this._onAdd) + collection.on('update', this._onUpdate) + collection.on('remove', this._onRemove) + } + + _detachCollection (collection) { + collection.removeListener('add', this._onAdd) + collection.removeListener('update', this._onUpdate) + collection.removeListener('remove', this._onRemove) + + clearObject(this._hashes) + } + + // ----------------------------------------------------------------- + + _onAdd (items) { + const { + computeHash, + _itemsByHash: itemsByHash, + _keysToHash: keysToHash + } = this + + for (let key in items) { + const value = items[key] + + const hash = computeHash(value, key) + + if (hash != null) { + ( + itemsByHash[hash] || + (itemsByHash[hash] = Object.create(null)) + )[key] = value + + keysToHash[key] = hash + } + } + } + + _onUpdate (items) { + const { + computeHash, + _itemsByHash: itemsByHash, + _keysToHash: keysToHash + } = this + + for (let key in items) { + const value = items[key] + + const prev = keysToHash[key] + const hash = computeHash(value, key) + if (hash === prev) { + continue + } + + if (prev != null) { + delete itemsByHash[prev][key] + } + + if (hash != null) { + ( + itemsByHash[hash] || + (itemsByHash[hash] = Object.create(null)) + )[key] = value + + keysToHash[key] = hash + } else { + delete keysToHash[key] + } + } + } + + _onRemove (items) { + const { + _itemsByHash: itemsByHash, + _keysToHash: keysToHash + } = this + + for (let key in items) { + const prev = keysToHash[key] + if (prev != null) { + delete keysToHash[key] + delete itemsByHash[prev][key] + } + } + } +} diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js new file mode 100644 index 000000000..0534784fe --- /dev/null +++ b/packages/xo-collection/src/index.spec.js @@ -0,0 +1,165 @@ +/* eslint-env mocha */ + +import chai, {expect} from 'chai' +import dirtyChai from 'dirty-chai' +chai.use(dirtyChai) + +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() + +import forEach from 'lodash.foreach' + +// ------------------------------------------------------------------- + +import Collection from './collection' +import Index from './index' + +// =================================================================== + +const waitTicks = (n = 1) => { + const {nextTick} = process + + return new Promise(resolve => { + (function waitNextTick () { + // The first tick is handled by Promise#then() + if (--n) { + nextTick(waitNextTick) + } else { + resolve() + } + })() + }) +} + +// =================================================================== + +describe('Index', function () { + let col, byGroup + const item1 = { + id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba', + group: 'foo' + } + const item2 = { + id: '7d21dc51-4da8-4538-a2e9-dd6f4784eb76', + group: 'bar' + } + const item3 = { + id: '668c1274-4442-44a6-b99a-512188e0bb09', + group: 'foo' + } + const item4 = { + id: 'd90b7335-e540-4a44-ad22-c4baae9cd0a9' + } + + beforeEach(function () { + col = new Collection() + forEach([item1, item2, item3, item4], item => { + col.add(item) + }) + + byGroup = new Index() + byGroup.computeHash = item => item.group + + col.createIndex('byGroup', byGroup) + + return waitTicks() + }) + + it('works with existing items', function () { + expect(col.indexes).to.eql({ + byGroup: { + foo: { + [item1.id]: item1, + [item3.id]: item3 + }, + bar: { + [item2.id]: item2 + } + } + }) + }) + + it('works with added items', function () { + const item5 = { + id: '823b56c4-4b96-4f3a-9533-5d08177167ac', + group: 'baz' + } + + col.add(item5) + + return waitTicks(2).then(() => { + expect(col.indexes).to.eql({ + byGroup: { + foo: { + [item1.id]: item1, + [item3.id]: item3 + }, + bar: { + [item2.id]: item2 + }, + baz: { + [item5.id]: item5 + } + } + }) + }) + }) + + it('works with updated items', function () { + const item1bis = { + id: item1.id, + group: 'bar' + } + + col.update(item1bis) + + return waitTicks(2).then(() => { + expect(col.indexes).to.eql({ + byGroup: { + foo: { + [item3.id]: item3 + }, + bar: { + [item1.id]: item1bis, + [item2.id]: item2 + } + } + }) + }) + }) + + it('works with removed items', function () { + col.remove(item2) + + return waitTicks(2).then(() => { + expect(col.indexes).to.eql({ + byGroup: { + foo: { + [item1.id]: item1, + [item3.id]: item3 + }, + bar: {} + } + }) + }) + }) + + describe('#sweep()', function () { + it('removes empty items lists', function () { + col.remove(item2) + + return waitTicks(2).then(() => { + byGroup.sweep() + + expect(col.indexes).to.eql({ + byGroup: { + foo: { + [item1.id]: item1, + [item3.id]: item3 + } + } + }) + }) + }) + }) +}) From d45348c16725677bf07c4d049876fb52b692e63a Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 27 Apr 2015 15:09:07 +0200 Subject: [PATCH 057/103] Minor fixes. --- packages/xo-collection/src/collection.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index c5f66eb1e..45c17140a 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -48,7 +48,7 @@ export class InvalidKey extends BaseError { } export class NoSuchIndex extends BaseError { - constructor (key) { + constructor (name) { super('there is no index with the name ' + name) } } @@ -205,7 +205,7 @@ export default class Collection extends EventEmitter { delete indexes[name] delete this._indexedItems[name] - index._detachCollection() + index._detachCollection(this) } // ----------------------------------------------------------------- From 1bc48fbf9667c9e7392d0c246832f2e7fe5f0eab Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 27 Apr 2015 15:27:12 +0200 Subject: [PATCH 058/103] 0.1.0 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index b81e3778a..d36e886b9 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.0.1", + "version": "0.1.0", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From 59dbee8f284e31fc3f00bcbb54c6c877185837da Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 28 Apr 2015 17:06:37 +0200 Subject: [PATCH 059/103] Minor doc about views. --- packages/xo-collection/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index f6367957c..cb905c115 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -179,6 +179,25 @@ for (let value of col.values()) { } ``` +### Views + +```javascript +const View = require('xo-collection/view') +``` + +> A view is a read-only collection which contains only the items of a +> parent collection which satisfy a predicate. +> +> It is updated at most once per turn of the event loop and therefore +> can be briefly invalid. + +```javascript +const myView = new View(parentCollection, function predicate (value, key) { + // This function should return a boolean indicating whether the + // current item should be in this view. +}) +``` + ## Development ### Installing dependencies From f5d5b5efc049c65a50aa49aab99e22c2ef153020 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 28 Apr 2015 17:10:31 +0200 Subject: [PATCH 060/103] Make View and Index requireable. --- packages/xo-collection/index.js | 1 + packages/xo-collection/src/collection.spec.js | 2 +- packages/xo-collection/src/index.spec.js | 4 ++-- packages/xo-collection/src/view.example.js | 4 ++-- packages/xo-collection/view.js | 1 + 5 files changed, 7 insertions(+), 5 deletions(-) create mode 100644 packages/xo-collection/index.js create mode 100644 packages/xo-collection/view.js diff --git a/packages/xo-collection/index.js b/packages/xo-collection/index.js new file mode 100644 index 000000000..aae59039c --- /dev/null +++ b/packages/xo-collection/index.js @@ -0,0 +1 @@ +module.exports = require('./dist/index') diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 883010824..8e3582665 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -1,6 +1,6 @@ /* eslint-env mocha */ -import Collection, {DuplicateItem, NoSuchItem} from './collection' +import Collection, {DuplicateItem, NoSuchItem} from '..' import eventToPromise from 'event-to-promise' import forEach from 'lodash.foreach' diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 0534784fe..1eed303d5 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -11,8 +11,8 @@ import forEach from 'lodash.foreach' // ------------------------------------------------------------------- -import Collection from './collection' -import Index from './index' +import Collection from '..' +import Index from '../index' // =================================================================== diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js index ef6e17b7a..f80ede21e 100644 --- a/packages/xo-collection/src/view.example.js +++ b/packages/xo-collection/src/view.example.js @@ -1,7 +1,7 @@ import forEach from 'lodash.foreach' -import Collection from './collection' -import View from './view' +import Collection from '..' +import View from '../view' // =================================================================== diff --git a/packages/xo-collection/view.js b/packages/xo-collection/view.js new file mode 100644 index 000000000..6e691e6c2 --- /dev/null +++ b/packages/xo-collection/view.js @@ -0,0 +1 @@ +module.exports = require('./dist/view') From 17ef6539032d4e53b325d760281fe76ef846d926 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 28 Apr 2015 17:10:58 +0200 Subject: [PATCH 061/103] 0.1.1 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index d36e886b9..943d89917 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.1.0", + "version": "0.1.1", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From e14dcd01847bd0efbd6e5a2f35600aa0f8daf280 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 13:13:39 +0200 Subject: [PATCH 062/103] Put some utils in their own modules. --- packages/xo-collection/src/clear-object.js | 5 ++++ packages/xo-collection/src/index.js | 27 +++---------------- packages/xo-collection/src/is-empty.js | 7 +++++ packages/xo-collection/src/not-implemented.js | 7 +++++ 4 files changed, 22 insertions(+), 24 deletions(-) create mode 100644 packages/xo-collection/src/clear-object.js create mode 100644 packages/xo-collection/src/is-empty.js create mode 100644 packages/xo-collection/src/not-implemented.js diff --git a/packages/xo-collection/src/clear-object.js b/packages/xo-collection/src/clear-object.js new file mode 100644 index 000000000..4e5882ac6 --- /dev/null +++ b/packages/xo-collection/src/clear-object.js @@ -0,0 +1,5 @@ +export default function clearObject (object) { + for (let key in object) { + delete object[key] + } +} diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index a4741d557..61aa811e5 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -1,29 +1,8 @@ import bind from 'lodash.bind' -import {BaseError} from 'make-error' -// =================================================================== - -class NotImplemented extends BaseError { - constructor (message) { - super(message || 'this method is not implemented') - } -} - -// =================================================================== - -const clearObject = (object) => { - for (let key in object) { - delete object[key] - } -} - -const isEmpty = (object) => { - /* eslint no-unused-vars: 0 */ - for (let key in object) { - return false - } - return true -} +import clearObject from './clear-object' +import isEmpty from './is-empty' +import NotImplemented from './not-implemented' // =================================================================== diff --git a/packages/xo-collection/src/is-empty.js b/packages/xo-collection/src/is-empty.js new file mode 100644 index 000000000..a3ad65cb1 --- /dev/null +++ b/packages/xo-collection/src/is-empty.js @@ -0,0 +1,7 @@ +export default function isEmpty (object) { + /* eslint no-unused-vars: 0 */ + for (let key in object) { + return false + } + return true +} diff --git a/packages/xo-collection/src/not-implemented.js b/packages/xo-collection/src/not-implemented.js new file mode 100644 index 000000000..52e507e37 --- /dev/null +++ b/packages/xo-collection/src/not-implemented.js @@ -0,0 +1,7 @@ +import {BaseError} from 'make-error' + +export default class NotImplemented extends BaseError { + constructor (message) { + super(message || 'this method is not implemented') + } +} From de6cbb0f45d8cc20f243d8af5863b64b9681a717 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 13:14:12 +0200 Subject: [PATCH 063/103] Fix Index#sweep(). --- packages/xo-collection/src/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 61aa811e5..3a321e619 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -58,7 +58,8 @@ export default class Index { collection.removeListener('update', this._onUpdate) collection.removeListener('remove', this._onRemove) - clearObject(this._hashes) + clearObject(this._itemsByHash) + clearObject(this._keysToHash) } // ----------------------------------------------------------------- From aebd9319f5e2e4cc5dc519dfb6fc39f66157b279 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 13:17:31 +0200 Subject: [PATCH 064/103] Comments in Collection#_onUpdate(). --- packages/xo-collection/src/index.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 3a321e619..5fb4b9392 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -99,14 +99,14 @@ export default class Index { const prev = keysToHash[key] const hash = computeHash(value, key) - if (hash === prev) { - continue - } - if (prev != null) { - delete itemsByHash[prev][key] - } + // Same hash, nothing to do. + if (hash === prev) continue + // Removes item from the previous hash's list if any. + if (prev != null) delete itemsByHash[prev][key] + + // Inserts item into the new hash's list if any. if (hash != null) { ( itemsByHash[hash] || From cd582e2e3af9df9062dff4b2ca7eb1b5f0d97459 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 14:12:22 +0200 Subject: [PATCH 065/103] Rename Index#itemsByHash to Index#items. --- packages/xo-collection/src/collection.js | 2 +- packages/xo-collection/src/index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 45c17140a..bd3c82482 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -192,7 +192,7 @@ export default class Collection extends EventEmitter { throw new DuplicateIndex(name) } indexes[name] = index - this._indexedItems[name] = index.itemsByHash + this._indexedItems[name] = index.items } deleteIndex (name) { diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 5fb4b9392..70ed04c9a 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -35,7 +35,7 @@ export default class Index { // ----------------------------------------------------------------- - get itemsByHash () { + get items () { return this._itemsByHash } From 0880787d680dbdaab19813d96e1f4c98ad2412e8 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 14:33:37 +0200 Subject: [PATCH 066/103] new Index() now accepts a computeHash() callback-ish. --- packages/xo-collection/package.json | 8 ++++---- packages/xo-collection/src/index.js | 7 ++++++- packages/xo-collection/src/index.spec.js | 3 +-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 943d89917..00c4e9270 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -21,10 +21,10 @@ ], "dependencies": { "babel-runtime": "^5", - "lodash.bind": "^3.1.0", - "lodash.callback": "^3.1.1", - "lodash.foreach": "^3.0.2", - "make-error": "^1.0.0" + "lodash.bind": "^3", + "lodash.callback": "^3", + "lodash.foreach": "^3", + "make-error": "^1" }, "devDependencies": { "babel": "^5", diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 70ed04c9a..aac48e146 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -1,4 +1,5 @@ import bind from 'lodash.bind' +import callback from 'lodash.callback' import clearObject from './clear-object' import isEmpty from './is-empty' @@ -7,7 +8,11 @@ import NotImplemented from './not-implemented' // =================================================================== export default class Index { - constructor () { + constructor (computeHash) { + if (computeHash) { + this.computeHash = callback(computeHash) + } + this._itemsByHash = Object.create(null) this._keysToHash = Object.create(null) diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 1eed303d5..2587f4a19 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -57,8 +57,7 @@ describe('Index', function () { col.add(item) }) - byGroup = new Index() - byGroup.computeHash = item => item.group + byGroup = new Index('group') col.createIndex('byGroup', byGroup) From e5f3ca162332ad854ae86e19ddfcc1768900f24d Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 17:51:18 +0200 Subject: [PATCH 067/103] Initial UniqueIndex. --- packages/xo-collection/src/unique-index.js | 123 +++++++++++++++ .../xo-collection/src/unique-index.spec.js | 144 ++++++++++++++++++ packages/xo-collection/unique-index.js | 1 + 3 files changed, 268 insertions(+) create mode 100644 packages/xo-collection/src/unique-index.js create mode 100644 packages/xo-collection/src/unique-index.spec.js create mode 100644 packages/xo-collection/unique-index.js diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js new file mode 100644 index 000000000..36e6cb13f --- /dev/null +++ b/packages/xo-collection/src/unique-index.js @@ -0,0 +1,123 @@ +import bind from 'lodash.bind' +import callback from 'lodash.callback' + +import clearObject from './clear-object' +import NotImplemented from './not-implemented' + +// =================================================================== + +export default class UniqueIndex { + constructor (computeHash) { + if (computeHash) { + this.computeHash = callback(computeHash) + } + + this._itemByHash = Object.create(null) + this._keysToHash = Object.create(null) + + // Bound versions of listeners. + this._onAdd = bind(this._onAdd, this) + this._onUpdate = bind(this._onUpdate, this) + this._onRemove = bind(this._onRemove, this) + } + + // This method is used to compute the hash under which an item must + // be saved. + computeHash (value, key) { + throw new NotImplemented('this method must be overridden') + } + + // ----------------------------------------------------------------- + + get items () { + return this._itemByHash + } + + // ----------------------------------------------------------------- + + _attachCollection (collection) { + // Add existing entries. + // + // FIXME: I think there may be a race condition if the `add` event + // has not been emitted yet. + this._onAdd(collection.all) + + collection.on('add', this._onAdd) + collection.on('update', this._onUpdate) + collection.on('remove', this._onRemove) + } + + _detachCollection (collection) { + collection.removeListener('add', this._onAdd) + collection.removeListener('update', this._onUpdate) + collection.removeListener('remove', this._onRemove) + + clearObject(this._itemByHash) + clearObject(this._keysToHash) + } + + // ----------------------------------------------------------------- + + _onAdd (items) { + const { + computeHash, + _itemByHash: itemByHash, + _keysToHash: keysToHash + } = this + + for (let key in items) { + const value = items[key] + + const hash = computeHash(value, key) + + if (hash != null) { + itemByHash[hash] = {key, value} + keysToHash[key] = hash + } + } + } + + _onUpdate (items) { + const { + computeHash, + _itemByHash: itemByHash, + _keysToHash: keysToHash + } = this + + for (let key in items) { + const value = items[key] + + const prev = keysToHash[key] + const hash = computeHash(value, key) + + // Same hash, nothing to do. + if (hash === prev) continue + + // Removes item from the previous hash's list if any. + if (prev != null) delete itemByHash[prev] + + // Inserts item into the new hash's list if any. + if (hash != null) { + keysToHash[key] = hash + itemByHash[hash] = {key, value} + } else { + delete keysToHash[key] + } + } + } + + _onRemove (items) { + const { + _itemByHash: itemByHash, + _keysToHash: keysToHash + } = this + + for (let key in items) { + const prev = keysToHash[key] + if (prev != null) { + delete keysToHash[key] + delete itemByHash[prev] + } + } + } +} diff --git a/packages/xo-collection/src/unique-index.spec.js b/packages/xo-collection/src/unique-index.spec.js new file mode 100644 index 000000000..cc62fa4fd --- /dev/null +++ b/packages/xo-collection/src/unique-index.spec.js @@ -0,0 +1,144 @@ +/* eslint-env mocha */ + +import chai, {expect} from 'chai' +import dirtyChai from 'dirty-chai' +chai.use(dirtyChai) + +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() + +import forEach from 'lodash.foreach' + +// ------------------------------------------------------------------- + +import Collection from '..' +import Index from '../unique-index' + +// =================================================================== + +const waitTicks = (n = 1) => { + const {nextTick} = process + + return new Promise(resolve => { + (function waitNextTick () { + // The first tick is handled by Promise#then() + if (--n) { + nextTick(waitNextTick) + } else { + resolve() + } + })() + }) +} + +// =================================================================== + +describe('UniqueIndex', function () { + let col, byKey + const item1 = { + id: '2ccb8a72-dc65-48e4-88fe-45ef541f2cba', + key: '036dee1b-9a3b-4fb5-be8a-4f535b355581' + } + const item2 = { + id: '7d21dc51-4da8-4538-a2e9-dd6f4784eb76', + key: '103cd893-d2cc-4d37-96fd-c259ad04c0d4' + } + const item3 = { + id: '668c1274-4442-44a6-b99a-512188e0bb09' + } + + beforeEach(function () { + col = new Collection() + forEach([item1, item2, item3], item => { + col.add(item) + }) + + byKey = new Index('key') + + col.createIndex('byKey', byKey) + + return waitTicks() + }) + + it('works with existing items', function () { + expect(col.indexes).to.eql({ + byKey: { + [item1.key]: { + key: item1.id, + value: item1 + }, + [item2.key]: { + key: item2.id, + value: item2 + } + } + }) + }) + + it('works with added items', function () { + const item4 = { + id: '823b56c4-4b96-4f3a-9533-5d08177167ac', + key: '1437af14-429a-40db-8a51-8a2f5ed03201' + } + + col.add(item4) + + return waitTicks(2).then(() => { + expect(col.indexes).to.eql({ + byKey: { + [item1.key]: { + key: item1.id, + value: item1 + }, + [item2.key]: { + key: item2.id, + value: item2 + }, + [item4.key]: { + key: item4.id, + value: item4 + } + } + }) + }) + }) + + it('works with updated items', function () { + const item1bis = { + id: item1.id, + key: 'e03d4a3a-0331-4aca-97a2-016bbd43a29b' + } + + col.update(item1bis) + + return waitTicks(2).then(() => { + expect(col.indexes).to.eql({ + byKey: { + [item1bis.key]: { + key: item1.id, + value: item1bis + }, + [item2.key]: { + key: item2.id, + value: item2 + } + } + }) + }) + }) + + it('works with removed items', function () { + col.remove(item2) + + return waitTicks(2).then(() => { + expect(col.indexes).to.eql({ + byKey: { + [item1.key]: { + key: item1.id, + value: item1 + } + } + }) + }) + }) +}) diff --git a/packages/xo-collection/unique-index.js b/packages/xo-collection/unique-index.js new file mode 100644 index 000000000..9f9d92cd5 --- /dev/null +++ b/packages/xo-collection/unique-index.js @@ -0,0 +1 @@ +module.exports = require('./dist/unique-index') From c804630576789ea2c33d63d5daf13fc452cecad3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 29 Apr 2015 18:17:39 +0200 Subject: [PATCH 068/103] 0.2.0 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 00c4e9270..1d03648ef 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.1.1", + "version": "0.2.0", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From bb35fc38011f2616932842047cf77ec3707f9f68 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 30 Apr 2015 11:44:53 +0200 Subject: [PATCH 069/103] Fix README title. --- packages/xo-collection/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index cb905c115..ccabddecf 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -1,4 +1,4 @@ -# collection [![Build Status](https://travis-ci.org/marsaud/collection.png?branch=master)](https://travis-ci.org/marsaud/collection) +# xo-collection [![Build Status](https://travis-ci.org/marsaud/collection.png?branch=master)](https://travis-ci.org/marsaud/collection) > Generic in-memory collection with events From e3ffc8784e1287e72c8da5e4733c7e06bb1c7c6d Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 30 Apr 2015 11:45:14 +0200 Subject: [PATCH 070/103] Use shared module instead of custom isNotEmpty(). --- packages/xo-collection/src/collection.js | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index bd3c82482..72de3294e 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -2,17 +2,10 @@ import forEach from 'lodash.foreach' import {BaseError} from 'make-error' import {EventEmitter} from 'events' +import isEmpty from './is-empty' + // =================================================================== -function isNotEmpty (map) { - /* eslint no-unused-vars: 0*/ - - for (let key in map) { - return true - } - return false -} - const {hasOwnProperty} = Object // =================================================================== @@ -267,7 +260,7 @@ export default class Collection extends EventEmitter { forEach(['add', 'update', 'remove'], action => { const items = data[action] - if (isNotEmpty(items)) { + if (!isEmpty(items)) { this.emit(action, items) } }) From a688310b95449fb420777501e1ab53f20f906e2f Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 4 May 2015 17:34:02 +0200 Subject: [PATCH 071/103] Remove thisArg param. --- packages/xo-collection/src/view.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index 358fe74cb..7b1107d7f 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -7,11 +7,11 @@ import Collection from './collection' // =================================================================== export default class View extends Collection { - constructor (collection, predicate, thisArg) { + constructor (collection, predicate) { super() this._collection = collection - this._predicate = createCallback(predicate, thisArg) + this._predicate = createCallback(predicate) // Handles initial items. this._onAdd(this._collection.all) From 1033bfcfe571293d2bd7941e643099e96e5074ac Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 14 May 2015 17:16:35 +0200 Subject: [PATCH 072/103] Add missing files. --- packages/xo-collection/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 1d03648ef..76fefad00 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -17,7 +17,8 @@ "preferGlobal": false, "main": "dist/collection", "files": [ - "dist/" + "dist/", + "*.js" ], "dependencies": { "babel-runtime": "^5", From 644ebd0a4f9d2674f0c402c6a2aa037cfb02ff89 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 14 May 2015 17:18:12 +0200 Subject: [PATCH 073/103] 0.2.1 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 76fefad00..537287f35 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.2.0", + "version": "0.2.1", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From e9639380161d7fa0b015ab929a3f013deea1d2aa Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 14:42:11 +0200 Subject: [PATCH 074/103] Do not attach collection to index if duplicate. --- packages/xo-collection/src/collection.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 72de3294e..c2f2684ff 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -178,14 +178,15 @@ export default class Collection extends EventEmitter { // ----------------------------------------------------------------- createIndex (name, index) { - index._attachCollection(this) - const {_indexes: indexes} = this if (hasOwnProperty.call(indexes, name)) { throw new DuplicateIndex(name) } + indexes[name] = index this._indexedItems[name] = index.items + + index._attachCollection(this) } deleteIndex (name) { From 3e7f1275d87483da4a7deb120188654f29df2cac Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 14:43:16 +0200 Subject: [PATCH 075/103] Remove unnecessary array. --- packages/xo-collection/src/collection.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index c2f2684ff..401584532 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -258,9 +258,7 @@ export default class Collection extends EventEmitter { data[this._buffer[key]][key] = this._items[key] } - forEach(['add', 'update', 'remove'], action => { - const items = data[action] - + forEach(data, (items, action) => { if (!isEmpty(items)) { this.emit(action, items) } From 7ddb57078c857d4c03c243ba8461912d498effa8 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 15:25:30 +0200 Subject: [PATCH 076/103] Finish event. --- packages/xo-collection/README.md | 11 +++++++++++ packages/xo-collection/src/collection.js | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index ccabddecf..96a669f7c 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -163,6 +163,17 @@ col.on('remove', (removed) => { }) ``` +**End of update** + +> Emitted when all the update process is finished and all the update +> events has been emitted. + +```javascript +col.on('finish', () => { + console.log('the collection has been updated') +}) +``` + ### Iteration ```javascript diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 401584532..632145629 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -248,6 +248,13 @@ export default class Collection extends EventEmitter { return } + const {_buffer: buffer} = this + + // Due to deduplication there could be nothing in the buffer. + if (isEmpty(buffer)) { + return + } + const data = { add: Object.create(null), remove: Object.create(null), @@ -255,7 +262,7 @@ export default class Collection extends EventEmitter { } for (let key in this._buffer) { - data[this._buffer[key]][key] = this._items[key] + data[buffer[key]][key] = this._items[key] } forEach(data, (items, action) => { @@ -264,6 +271,12 @@ export default class Collection extends EventEmitter { } }) + // Indicates the end of the update. + // + // This name has been chosen because it is used in Node writable + // streams when the data has been successfully committed. + this.emit('finish') + this._buffer = Object.create(null) } } From f9c26089cd09aef37c66757427daef4c68395f42 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 15:25:44 +0200 Subject: [PATCH 077/103] Document exceptions. --- packages/xo-collection/README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 96a669f7c..50ed2bded 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -31,12 +31,16 @@ var col = new Collection() col.add('foo', true) ``` +- **Throws** `DuplicateItem` if the item is already in the collection. + **Updating an existing item** ```javascript col.update('foo', false) ``` +- **Throws** `NoSuchItem` if the item is not in the collection. + **Inserting or updating an item** ```javascript @@ -67,12 +71,17 @@ col.touch('baz') col.touch('baz').prop = false ``` +- **Throws** `NoSuchItem` if the item is not in the collection. +- **Throws** `IllegalTouch` if the item is not an object. + **Removing an existing item** ```javascript col.remove('bar') ``` +- **Throws** `NoSuchItem` if the item is not in the collection. + **Removing all items** ```javascript @@ -97,6 +106,9 @@ var foo = col.get('foo') var bar = col.get('bar', 6.28) ``` +- **Throws** `NoSuchItem` if the item is not in the collection and no + fallback has been passed. + **Getting a read-only view of the collection** > This property is useful for example to iterate over the collection From bd12ade4264a52916e7dd2878f3a32d7ec172b01 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 16:34:48 +0200 Subject: [PATCH 078/103] UniqueIndex only expose the values of contained items. --- packages/xo-collection/src/unique-index.js | 4 +- .../xo-collection/src/unique-index.spec.js | 40 ++++--------------- 2 files changed, 10 insertions(+), 34 deletions(-) diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index 36e6cb13f..321bcf4cc 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -71,7 +71,7 @@ export default class UniqueIndex { const hash = computeHash(value, key) if (hash != null) { - itemByHash[hash] = {key, value} + itemByHash[hash] = value keysToHash[key] = hash } } @@ -98,8 +98,8 @@ export default class UniqueIndex { // Inserts item into the new hash's list if any. if (hash != null) { + itemByHash[hash] = value keysToHash[key] = hash - itemByHash[hash] = {key, value} } else { delete keysToHash[key] } diff --git a/packages/xo-collection/src/unique-index.spec.js b/packages/xo-collection/src/unique-index.spec.js index cc62fa4fd..a4000ff60 100644 --- a/packages/xo-collection/src/unique-index.spec.js +++ b/packages/xo-collection/src/unique-index.spec.js @@ -63,14 +63,8 @@ describe('UniqueIndex', function () { it('works with existing items', function () { expect(col.indexes).to.eql({ byKey: { - [item1.key]: { - key: item1.id, - value: item1 - }, - [item2.key]: { - key: item2.id, - value: item2 - } + [item1.key]: item1, + [item2.key]: item2 } }) }) @@ -86,18 +80,9 @@ describe('UniqueIndex', function () { return waitTicks(2).then(() => { expect(col.indexes).to.eql({ byKey: { - [item1.key]: { - key: item1.id, - value: item1 - }, - [item2.key]: { - key: item2.id, - value: item2 - }, - [item4.key]: { - key: item4.id, - value: item4 - } + [item1.key]: item1, + [item2.key]: item2, + [item4.key]: item4 } }) }) @@ -114,14 +99,8 @@ describe('UniqueIndex', function () { return waitTicks(2).then(() => { expect(col.indexes).to.eql({ byKey: { - [item1bis.key]: { - key: item1.id, - value: item1bis - }, - [item2.key]: { - key: item2.id, - value: item2 - } + [item1bis.key]: item1bis, + [item2.key]: item2 } }) }) @@ -133,10 +112,7 @@ describe('UniqueIndex', function () { return waitTicks(2).then(() => { expect(col.indexes).to.eql({ byKey: { - [item1.key]: { - key: item1.id, - value: item1 - } + [item1.key]: item1 } }) }) From aeadbc1d58811a544d8427e13db54aa10ed3161d Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 16:35:23 +0200 Subject: [PATCH 079/103] Minor standardization. --- packages/xo-collection/src/index.js | 2 +- packages/xo-collection/src/unique-index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index aac48e146..2842f9bbd 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -134,8 +134,8 @@ export default class Index { for (let key in items) { const prev = keysToHash[key] if (prev != null) { - delete keysToHash[key] delete itemsByHash[prev][key] + delete keysToHash[key] } } } diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index 321bcf4cc..eb70ef71c 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -115,8 +115,8 @@ export default class UniqueIndex { for (let key in items) { const prev = keysToHash[key] if (prev != null) { - delete keysToHash[key] delete itemByHash[prev] + delete keysToHash[key] } } } From 41205aef200233d4dce69dc1cac2d352e529c168 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 16:38:02 +0200 Subject: [PATCH 080/103] Work around xo-web bug due to Angular. --- packages/xo-collection/src/index.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 2842f9bbd..5b507da33 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -84,7 +84,11 @@ export default class Index { if (hash != null) { ( itemsByHash[hash] || - (itemsByHash[hash] = Object.create(null)) + + // FIXME: We do not use objects without prototype for now + // because it breaks Angular in xo-web, change it back when + // this is fixed. + (itemsByHash[hash] = {}) )[key] = value keysToHash[key] = hash @@ -115,7 +119,9 @@ export default class Index { if (hash != null) { ( itemsByHash[hash] || - (itemsByHash[hash] = Object.create(null)) + + // FIXME: idem: change back to Object.create(null) + (itemsByHash[hash] = {}) )[key] = value keysToHash[key] = hash From d55fb36182c295c4e3f52bdc7cd7c580c76952e3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 19 May 2015 16:39:54 +0200 Subject: [PATCH 081/103] 0.3.0 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 537287f35..f64fa8fcb 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.2.1", + "version": "0.3.0", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From 47c45160602e8d443622f36401654ac2480e01a7 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 22 May 2015 14:46:20 +0200 Subject: [PATCH 082/103] Index & UniqueIndex: Correctly updates even if the hash has not changed. --- packages/xo-collection/src/index.js | 3 --- packages/xo-collection/src/index.spec.js | 25 +++++++++++++++++++ packages/xo-collection/src/unique-index.js | 3 --- .../xo-collection/src/unique-index.spec.js | 20 +++++++++++++++ 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 5b507da33..76c1af5d7 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -109,9 +109,6 @@ export default class Index { const prev = keysToHash[key] const hash = computeHash(value, key) - // Same hash, nothing to do. - if (hash === prev) continue - // Removes item from the previous hash's list if any. if (prev != null) delete itemsByHash[prev][key] diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 2587f4a19..715025102 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -7,6 +7,7 @@ chai.use(dirtyChai) import sourceMapSupport from 'source-map-support' sourceMapSupport.install() +import eventToPromise from 'event-to-promise' import forEach from 'lodash.foreach' // ------------------------------------------------------------------- @@ -143,6 +144,30 @@ describe('Index', function () { }) }) + it('correctly updates the value even the same object has the same hash', function () { + const item1bis = { + id: item1.id, + group: item1.group, + newProp: true + } + + col.update(item1bis) + + return eventToPromise(col, 'finish').then(() => { + expect(col.indexes).to.eql({ + byGroup: { + foo: { + [item1.id]: item1bis, + [item3.id]: item3 + }, + bar: { + [item2.id]: item2 + } + } + }) + }) + }) + describe('#sweep()', function () { it('removes empty items lists', function () { col.remove(item2) diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index eb70ef71c..6153bbe61 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -90,9 +90,6 @@ export default class UniqueIndex { const prev = keysToHash[key] const hash = computeHash(value, key) - // Same hash, nothing to do. - if (hash === prev) continue - // Removes item from the previous hash's list if any. if (prev != null) delete itemByHash[prev] diff --git a/packages/xo-collection/src/unique-index.spec.js b/packages/xo-collection/src/unique-index.spec.js index a4000ff60..c4fb09ec6 100644 --- a/packages/xo-collection/src/unique-index.spec.js +++ b/packages/xo-collection/src/unique-index.spec.js @@ -7,6 +7,7 @@ chai.use(dirtyChai) import sourceMapSupport from 'source-map-support' sourceMapSupport.install() +import eventToPromise from 'event-to-promise' import forEach from 'lodash.foreach' // ------------------------------------------------------------------- @@ -117,4 +118,23 @@ describe('UniqueIndex', function () { }) }) }) + + it('correctly updates the value even the same object has the same hash', function () { + const item1bis = { + id: item1.id, + key: item1.key, + newProp: true + } + + col.update(item1bis) + + return eventToPromise(col, 'finish').then(() => { + expect(col.indexes).to.eql({ + byKey: { + [item1.key]: item1bis, + [item2.key]: item2 + } + }) + }) + }) }) From 811e0123c926f39026ffb8200fb9d069fec3b6d5 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 22 May 2015 14:46:46 +0200 Subject: [PATCH 083/103] 0.3.1 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index f64fa8fcb..fb40ce3cc 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.3.0", + "version": "0.3.1", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From 4d2e42d24490b316ed7ff8efbc2b3eb9af5c4ffd Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sun, 24 May 2015 14:39:48 +0200 Subject: [PATCH 084/103] One more Angular work around. --- packages/xo-collection/src/collection.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 632145629..534ad02cc 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -62,7 +62,7 @@ export default class Collection extends EventEmitter { this._buffering = 0 this._indexes = Object.create(null) this._indexedItems = Object.create(null) - this._items = Object.create(null) + this._items = {} // Object.create(null) this._size = 0 } From 7c54adec9ddadda016582526208136bfca5b4809 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Sun, 24 May 2015 14:41:22 +0200 Subject: [PATCH 085/103] 0.3.2 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index fb40ce3cc..7bc292eba 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.3.1", + "version": "0.3.2", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From ce15dbf31b528a60201ac31a1d4c2759c80f0f30 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 26 Jun 2015 11:20:50 +0200 Subject: [PATCH 086/103] New Collection#unset(). --- packages/xo-collection/README.md | 9 ++++++ packages/xo-collection/src/collection.js | 10 +++++++ packages/xo-collection/src/collection.spec.js | 28 +++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 50ed2bded..3659b46d9 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -82,6 +82,15 @@ col.remove('bar') - **Throws** `NoSuchItem` if the item is not in the collection. +**Removing an item without error** + +This is the symmetric method of `set()`: it removes the item if it +exists otherwise does nothing. + +```javascript +col.unset('bar') +``` + **Removing all items** ```javascript diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 534ad02cc..6b312f6a6 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -144,6 +144,16 @@ export default class Collection extends EventEmitter { return this.get(key) } + unset (keyOrObjectWithId) { + const [key] = this._resolveItem(keyOrObjectWithId) + + if (this.has(key)) { + delete this._items[key] + this._size-- + this._touch('remove', key) + } + } + update (keyOrObjectWithId, valueIfKey = undefined) { const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) this._assertHas(key) diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 8e3582665..1dc4955d7 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -204,6 +204,34 @@ describe('Collection', function () { }) }) + describe('#unset()', function () { + it('removes an existing item', function () { + this.col.unset('bar') + + expect(this.col.has('bar')).to.be.false() + + return eventToPromise(this.col, 'remove').then(function (removed) { + expect(removed).to.have.all.keys('bar') + expect(removed.bar).to.not.exist() + }) + }) + + it('does not throw if the item does not exists', function () { + this.col.unset('foo') + }) + + it('accepts an object with an id property', function () { + this.col.unset({id: 'bar'}) + + expect(this.col.has('bar')).to.be.false() + + return eventToPromise(this.col, 'remove').then(function (removed) { + expect(removed).to.have.all.keys('bar') + expect(removed.bar).to.not.exist() + }) + }) + }) + describe('touch()', function () { it('can be used to signal an indirect update', function () { const foo = { id: 'foo' } From dfc312c0925e03b66ac1c8e9a0b7f730fe27a24f Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 26 Jun 2015 11:57:41 +0200 Subject: [PATCH 087/103] Various updates. --- packages/xo-collection/.babelrc | 15 ++++++++ packages/xo-collection/.gitignore | 1 + packages/xo-collection/.mocha.js | 3 ++ packages/xo-collection/.mocha.opts | 1 + packages/xo-collection/.npmignore | 6 +++ packages/xo-collection/.travis.yml | 5 ++- packages/xo-collection/package.json | 37 +++++++++++-------- packages/xo-collection/src/collection.spec.js | 30 +++++++-------- packages/xo-collection/src/index.spec.js | 10 +---- .../xo-collection/src/unique-index.spec.js | 10 +---- 10 files changed, 68 insertions(+), 50 deletions(-) create mode 100644 packages/xo-collection/.babelrc create mode 100644 packages/xo-collection/.mocha.js create mode 100644 packages/xo-collection/.mocha.opts diff --git a/packages/xo-collection/.babelrc b/packages/xo-collection/.babelrc new file mode 100644 index 000000000..5e9978a41 --- /dev/null +++ b/packages/xo-collection/.babelrc @@ -0,0 +1,15 @@ +{ + "comments": false, + "compact": true, + "optional": [ + // Experimental features. + // "minification.constantFolding", + // "minification.deadCodeElimination", + + "es7.asyncFunctions", + "es7.decorators", + "es7.exportExtensions", + "es7.functionBind", + "runtime" + ] +} diff --git a/packages/xo-collection/.gitignore b/packages/xo-collection/.gitignore index a4a5666f8..384949d8a 100644 --- a/packages/xo-collection/.gitignore +++ b/packages/xo-collection/.gitignore @@ -2,6 +2,7 @@ /dist/ npm-debug.log +npm-debug.log.* !node_modules/* node_modules/*/ diff --git a/packages/xo-collection/.mocha.js b/packages/xo-collection/.mocha.js new file mode 100644 index 000000000..b888fb4d5 --- /dev/null +++ b/packages/xo-collection/.mocha.js @@ -0,0 +1,3 @@ +try { require('clarify') } catch (_) {} +try { require('trace') } catch (_) {} +try { require('source-map-support/register') } catch (_) {} diff --git a/packages/xo-collection/.mocha.opts b/packages/xo-collection/.mocha.opts new file mode 100644 index 000000000..6cfd94898 --- /dev/null +++ b/packages/xo-collection/.mocha.opts @@ -0,0 +1 @@ +--require ./.mocha.js diff --git a/packages/xo-collection/.npmignore b/packages/xo-collection/.npmignore index 815f54c57..c31ee82cb 100644 --- a/packages/xo-collection/.npmignore +++ b/packages/xo-collection/.npmignore @@ -1,4 +1,10 @@ +/examples/ +example.js +example.js.map *.example.js *.example.js.map + +/test/ +/tests/ *.spec.js *.spec.js.map diff --git a/packages/xo-collection/.travis.yml b/packages/xo-collection/.travis.yml index 5227e1127..d38f7e60a 100644 --- a/packages/xo-collection/.travis.yml +++ b/packages/xo-collection/.travis.yml @@ -1,5 +1,6 @@ language: node_js node_js: - - 'iojs' + - 'iojs-v2' + - 'iojs-v1' - '0.12' - - '0.10' \ No newline at end of file + - '0.10' diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 7bc292eba..0c9c87c73 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -16,39 +16,44 @@ }, "preferGlobal": false, "main": "dist/collection", + "bin": {}, "files": [ "dist/", "*.js" ], "dependencies": { - "babel-runtime": "^5", - "lodash.bind": "^3", - "lodash.callback": "^3", - "lodash.foreach": "^3", - "make-error": "^1" + "babel-runtime": "^5.6.11", + "lodash.bind": "^3.1.0", + "lodash.callback": "^3.3.0", + "lodash.foreach": "^3.0.3", + "make-error": "^1.0.2" }, "devDependencies": { - "babel": "^5", - "chai": "*", - "dirty-chai": "^1.2.0", + "babel": "^5.6.11", + "babel-eslint": "^3.1.18", + "clarify": "^1.0.5", "event-to-promise": "^0.3.2", "ghooks": "^0.3.2", - "mocha": "*", + "mocha": "^2.2.5", + "must": "^0.12.0", "sinon": "^1.14.1", - "source-map-support": "*", - "standard": "*" + "source-map-support": "^0.3.2", + "standard": "^4.3.3", + "trace": "^1.2.0" }, "scripts": { - "build": "mkdir -p dist && babel --optional=runtime --compact=true --source-maps --out-dir=dist/ src/", - "dev": "mkdir -p dist && babel --watch --optional=runtime --source-maps --out-dir=dist/ src/", + "build": "babel --source-maps --out-dir=dist/ src/", + "dev": "babel --watch --source-maps --out-dir=dist/ src/", + "lint": "standard", "prepublish": "npm run build", - "test": "mocha 'dist/**/*.spec.js'", - "test-dev": "mocha --watch --reporter=min 'dist/**/*.spec.js'" + "test": "npm run lint && mocha --opts .mocha.opts \"dist/**/*.spec.js\"", + "test-dev": "mocha --opts .mocha.opts --watch --reporter=min \"dist/**/*.spec.js\"" }, "standard": { "ignore": [ "dist/**" - ] + ], + "parser": "babel-eslint" }, "config": { "ghooks": { diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 1dc4955d7..773cb45d8 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -1,17 +1,15 @@ /* eslint-env mocha */ -import Collection, {DuplicateItem, NoSuchItem} from '..' - import eventToPromise from 'event-to-promise' +import expect from 'must' import forEach from 'lodash.foreach' import sinon from 'sinon' -import chai, {expect} from 'chai' -import dirtyChai from 'dirty-chai' -chai.use(dirtyChai) +// =================================================================== -import sourceMapSupport from 'source-map-support' -sourceMapSupport.install() +import Collection, {DuplicateItem, NoSuchItem} from '..' + +// =================================================================== function waitTicks (n = 1) { const {nextTick} = process @@ -75,7 +73,7 @@ describe('Collection', function () { // Async event. return eventToPromise(this.col, 'add').then(function (added) { - expect(added).to.have.all.keys('foo') + expect(added).to.have.keys(['foo']) expect(added.foo).to.be.true() }) }) @@ -108,7 +106,7 @@ describe('Collection', function () { // Async event. return eventToPromise(this.col, 'update').then(function (updated) { - expect(updated).to.have.all.keys('bar') + expect(updated).to.have.keys(['bar']) expect(updated.bar).to.equal(2) }) }) @@ -140,7 +138,7 @@ describe('Collection', function () { // Async event. return eventToPromise(this.col, 'remove').then(function (removed) { - expect(removed).to.have.all.keys('bar') + expect(removed).to.have.keys(['bar']) expect(removed.bar).to.not.exist() }) }) @@ -172,7 +170,7 @@ describe('Collection', function () { // Async events. return eventToPromise(this.col, 'add').then(function (added) { - expect(added).to.have.all.keys('foo') + expect(added).to.have.keys(['foo']) expect(added.foo).to.be.true() }) }) @@ -190,7 +188,7 @@ describe('Collection', function () { // Async events. return eventToPromise(this.col, 'update').then(function (updated) { - expect(updated).to.have.all.keys('bar') + expect(updated).to.have.keys(['bar']) expect(updated.bar).to.equal(1) }) }) @@ -211,7 +209,7 @@ describe('Collection', function () { expect(this.col.has('bar')).to.be.false() return eventToPromise(this.col, 'remove').then(function (removed) { - expect(removed).to.have.all.keys('bar') + expect(removed).to.have.keys(['bar']) expect(removed.bar).to.not.exist() }) }) @@ -226,7 +224,7 @@ describe('Collection', function () { expect(this.col.has('bar')).to.be.false() return eventToPromise(this.col, 'remove').then(function (removed) { - expect(removed).to.have.all.keys('bar') + expect(removed).to.have.keys(['bar']) expect(removed.bar).to.not.exist() }) }) @@ -241,7 +239,7 @@ describe('Collection', function () { this.col.touch(foo) return eventToPromise(this.col, 'update', (items) => { - expect(items).to.have.all.keys('foo') + expect(items).to.have.keys(['foo']) expect(items.foo).to.equal(foo) }) }) @@ -255,7 +253,7 @@ describe('Collection', function () { expect(this.col.size).to.equal(0) return eventToPromise(this.col, 'remove').then((items) => { - expect(items).to.have.all.keys('bar') + expect(items).to.have.keys(['bar']) expect(items.bar).to.not.exist() }) }) diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 715025102..298b13ea2 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -1,16 +1,10 @@ /* eslint-env mocha */ -import chai, {expect} from 'chai' -import dirtyChai from 'dirty-chai' -chai.use(dirtyChai) - -import sourceMapSupport from 'source-map-support' -sourceMapSupport.install() - import eventToPromise from 'event-to-promise' +import expect from 'must' import forEach from 'lodash.foreach' -// ------------------------------------------------------------------- +// =================================================================== import Collection from '..' import Index from '../index' diff --git a/packages/xo-collection/src/unique-index.spec.js b/packages/xo-collection/src/unique-index.spec.js index c4fb09ec6..a7649362c 100644 --- a/packages/xo-collection/src/unique-index.spec.js +++ b/packages/xo-collection/src/unique-index.spec.js @@ -1,16 +1,10 @@ /* eslint-env mocha */ -import chai, {expect} from 'chai' -import dirtyChai from 'dirty-chai' -chai.use(dirtyChai) - -import sourceMapSupport from 'source-map-support' -sourceMapSupport.install() - import eventToPromise from 'event-to-promise' +import expect from 'must' import forEach from 'lodash.foreach' -// ------------------------------------------------------------------- +// =================================================================== import Collection from '..' import Index from '../unique-index' From 8de2066634849622f2947f87f06bb64318418ccb Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 26 Jun 2015 12:01:51 +0200 Subject: [PATCH 088/103] 0.4.0 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 0c9c87c73..31f85e22d 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.3.2", + "version": "0.4.0", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From ad10d13a755ef370fef670b9a5bb62275dea6b76 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 1 Oct 2015 18:23:17 +0200 Subject: [PATCH 089/103] Update standard. --- packages/xo-collection/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 31f85e22d..5401699c2 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -30,7 +30,7 @@ }, "devDependencies": { "babel": "^5.6.11", - "babel-eslint": "^3.1.18", + "babel-eslint": "^4.1.3", "clarify": "^1.0.5", "event-to-promise": "^0.3.2", "ghooks": "^0.3.2", @@ -38,7 +38,7 @@ "must": "^0.12.0", "sinon": "^1.14.1", "source-map-support": "^0.3.2", - "standard": "^4.3.3", + "standard": "^5.3.1", "trace": "^1.2.0" }, "scripts": { From ee53433dccd07518feb68a504fdf3cc4abf9bd74 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 1 Oct 2015 18:25:01 +0200 Subject: [PATCH 090/103] Use const wherever possible. --- packages/xo-collection/README.md | 6 +++--- packages/xo-collection/src/clear-object.js | 2 +- packages/xo-collection/src/collection.js | 8 ++++---- packages/xo-collection/src/index.js | 8 ++++---- packages/xo-collection/src/is-empty.js | 2 +- packages/xo-collection/src/unique-index.js | 6 +++--- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 3659b46d9..327af3662 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -198,15 +198,15 @@ col.on('finish', () => { ### Iteration ```javascript -for (let [key, value] of col) { +for (const [key, value] of col) { console.log('- %s: %j', key, value) } -for (let key of col.keys()) { +for (const key of col.keys()) { console.log('- %s', key) } -for (let value of col.values()) { +for (const value of col.values()) { console.log('- %j', value) } ``` diff --git a/packages/xo-collection/src/clear-object.js b/packages/xo-collection/src/clear-object.js index 4e5882ac6..0250f65c2 100644 --- a/packages/xo-collection/src/clear-object.js +++ b/packages/xo-collection/src/clear-object.js @@ -1,5 +1,5 @@ export default function clearObject (object) { - for (let key in object) { + for (const key in object) { delete object[key] } } diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 6b312f6a6..72a72d78e 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -219,7 +219,7 @@ export default class Collection extends EventEmitter { * [Symbol.iterator] () { const {_items: items} = this - for (let key in items) { + for (const key in items) { yield [key, items[key]] } } @@ -227,7 +227,7 @@ export default class Collection extends EventEmitter { * keys () { const {_items: items} = this - for (let key in items) { + for (const key in items) { yield key } } @@ -235,7 +235,7 @@ export default class Collection extends EventEmitter { * values () { const {_items: items} = this - for (let key in items) { + for (const key in items) { yield items[key] } } @@ -271,7 +271,7 @@ export default class Collection extends EventEmitter { update: Object.create(null) } - for (let key in this._buffer) { + for (const key in this._buffer) { data[buffer[key]][key] = this._items[key] } diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 76c1af5d7..78535713c 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -31,7 +31,7 @@ export default class Index { // Remove empty items lists. sweep () { const {_itemsByHash: itemsByHash} = this - for (let hash in itemsByHash) { + for (const hash in itemsByHash) { if (isEmpty(itemsByHash[hash])) { delete itemsByHash[hash] } @@ -76,7 +76,7 @@ export default class Index { _keysToHash: keysToHash } = this - for (let key in items) { + for (const key in items) { const value = items[key] const hash = computeHash(value, key) @@ -103,7 +103,7 @@ export default class Index { _keysToHash: keysToHash } = this - for (let key in items) { + for (const key in items) { const value = items[key] const prev = keysToHash[key] @@ -134,7 +134,7 @@ export default class Index { _keysToHash: keysToHash } = this - for (let key in items) { + for (const key in items) { const prev = keysToHash[key] if (prev != null) { delete itemsByHash[prev][key] diff --git a/packages/xo-collection/src/is-empty.js b/packages/xo-collection/src/is-empty.js index a3ad65cb1..9e688ac7c 100644 --- a/packages/xo-collection/src/is-empty.js +++ b/packages/xo-collection/src/is-empty.js @@ -1,6 +1,6 @@ export default function isEmpty (object) { /* eslint no-unused-vars: 0 */ - for (let key in object) { + for (const key in object) { return false } return true diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index 6153bbe61..8a1d91b70 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -65,7 +65,7 @@ export default class UniqueIndex { _keysToHash: keysToHash } = this - for (let key in items) { + for (const key in items) { const value = items[key] const hash = computeHash(value, key) @@ -84,7 +84,7 @@ export default class UniqueIndex { _keysToHash: keysToHash } = this - for (let key in items) { + for (const key in items) { const value = items[key] const prev = keysToHash[key] @@ -109,7 +109,7 @@ export default class UniqueIndex { _keysToHash: keysToHash } = this - for (let key in items) { + for (const key in items) { const prev = keysToHash[key] if (prev != null) { delete itemByHash[prev] From 083f32507608fb4c05227b37fdd5d3264da52855 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 1 Oct 2015 20:31:43 +0200 Subject: [PATCH 091/103] Temporary work around for eslint/eslint#3946. --- packages/xo-collection/src/view.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index 7b1107d7f..b7c318b5c 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -70,7 +70,7 @@ export default class View extends Collection { forEach(items, (value, key) => { if (predicate(value, key, this)) { super.set(key, value) - } else if (super.has(key)) { + } else if (super.has(key)) { // eslint-disable-line space-before-keywords super.remove(key) } }) @@ -78,7 +78,7 @@ export default class View extends Collection { _onRemove (items) { forEach(items, (value, key) => { - if (super.has(key)) { + if (super.has(key)) { // eslint-disable-line space-before-keywords super.remove(key) } }) From c439daadada992258f3ec932374957e0ff821daa Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 1 Oct 2015 20:43:27 +0200 Subject: [PATCH 092/103] Minor opt. --- packages/xo-collection/src/collection.js | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 72a72d78e..e50341909 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -6,7 +6,10 @@ import isEmpty from './is-empty' // =================================================================== -const {hasOwnProperty} = Object +const { + create: createObject, + hasOwnProperty +} = Object // =================================================================== @@ -58,11 +61,11 @@ export default class Collection extends EventEmitter { constructor () { super() - this._buffer = Object.create(null) + this._buffer = createObject(null) this._buffering = 0 - this._indexes = Object.create(null) - this._indexedItems = Object.create(null) - this._items = {} // Object.create(null) + this._indexes = createObject(null) + this._indexedItems = createObject(null) + this._items = {} // createObject(null) this._size = 0 } @@ -266,9 +269,9 @@ export default class Collection extends EventEmitter { } const data = { - add: Object.create(null), - remove: Object.create(null), - update: Object.create(null) + add: createObject(null), + remove: createObject(null), + update: createObject(null) } for (const key in this._buffer) { @@ -287,7 +290,7 @@ export default class Collection extends EventEmitter { // streams when the data has been successfully committed. this.emit('finish') - this._buffer = Object.create(null) + this._buffer = createObject(null) } } From 2071a7d3089c73919b955002136aaf9287318324 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 1 Oct 2015 20:47:32 +0200 Subject: [PATCH 093/103] Use kindof instead of typeof where appropriate. --- packages/xo-collection/package.json | 1 + packages/xo-collection/src/collection.js | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 5401699c2..f7f6a18f0 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -23,6 +23,7 @@ ], "dependencies": { "babel-runtime": "^5.6.11", + "kindof": "^2.0.0", "lodash.bind": "^3.1.0", "lodash.callback": "^3.3.0", "lodash.foreach": "^3.0.3", diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index e50341909..d404fce51 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -1,4 +1,5 @@ import forEach from 'lodash.foreach' +import kindOf from 'kindof' import {BaseError} from 'make-error' import {EventEmitter} from 'events' @@ -33,13 +34,13 @@ export class DuplicateItem extends BaseError { export class IllegalTouch extends BaseError { constructor (value) { - super('only an object value can be touched (found a ' + typeof value + ')') + super('only an object value can be touched (found a ' + kindOf(value) + ')') } } export class InvalidKey extends BaseError { constructor (key) { - super('invalid key of type ' + typeof key) + super('invalid key of type ' + kindOf(key)) } } @@ -138,7 +139,7 @@ export default class Collection extends EventEmitter { const [key] = this._resolveItem(keyOrObjectWithId) this._assertHas(key) const value = this.get(key) - if (typeof value !== 'object' || value === null) { + if (kindOf(value) !== 'object') { throw new IllegalTouch(value) } From 73821b0f12aa9110928b5752d80872e1c4e38f3c Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 2 Oct 2015 12:26:54 +0200 Subject: [PATCH 094/103] Isolate isObject(). --- packages/xo-collection/src/collection.js | 3 ++- packages/xo-collection/src/is-object.js | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 packages/xo-collection/src/is-object.js diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index d404fce51..84388f2fc 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -4,6 +4,7 @@ import {BaseError} from 'make-error' import {EventEmitter} from 'events' import isEmpty from './is-empty' +import isObject from './is-object' // =================================================================== @@ -139,7 +140,7 @@ export default class Collection extends EventEmitter { const [key] = this._resolveItem(keyOrObjectWithId) this._assertHas(key) const value = this.get(key) - if (kindOf(value) !== 'object') { + if (!isObject(value)) { throw new IllegalTouch(value) } diff --git a/packages/xo-collection/src/is-object.js b/packages/xo-collection/src/is-object.js new file mode 100644 index 000000000..737694cb7 --- /dev/null +++ b/packages/xo-collection/src/is-object.js @@ -0,0 +1,3 @@ +export function isObject (value) { + return (value !== null) && (typeof value === 'object') +} From 7d7e6e10b9737bdce655f9fe149402827ad7f0f3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 2 Oct 2015 12:27:18 +0200 Subject: [PATCH 095/103] Properly use Object.prototype.hasOwnProperty(). --- packages/xo-collection/src/collection.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 84388f2fc..8d9c74480 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -10,7 +10,7 @@ import isObject from './is-object' const { create: createObject, - hasOwnProperty + prototype: { hasOwnProperty } } = Object // =================================================================== From 43a362d0eb1d330e9ca9bdfbe568dd326a2a7ba2 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 2 Oct 2015 12:56:39 +0200 Subject: [PATCH 096/103] Use constants for code robustness & performance. --- packages/xo-collection/src/collection.js | 32 ++++++++++++---------- packages/xo-collection/src/index.js | 17 ++++++++---- packages/xo-collection/src/unique-index.js | 17 ++++++++---- packages/xo-collection/src/view.js | 18 +++++++----- 4 files changed, 51 insertions(+), 33 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 8d9c74480..9875b4ff5 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -13,6 +13,10 @@ const { prototype: { hasOwnProperty } } = Object +export const ACTION_ADD = 'add' +export const ACTION_UPDATE = 'update' +export const ACTION_REMOVE = 'remove' + // =================================================================== export class BufferAlreadyFlushed extends BaseError { @@ -105,14 +109,14 @@ export default class Collection extends EventEmitter { this._items[key] = value this._size++ - this._touch('add', key) + this._touch(ACTION_ADD, key) } clear () { forEach(this._items, (_, key) => { delete this._items[key] this._size-- - this._touch('remove', key) + this._touch(ACTION_REMOVE, key) }) } @@ -122,15 +126,15 @@ export default class Collection extends EventEmitter { delete this._items[key] this._size-- - this._touch('remove', key) + this._touch(ACTION_REMOVE, key) } set (keyOrObjectWithId, valueIfKey = undefined) { const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) - const action = this.has(key) ? 'update' : 'add' + const action = this.has(key) ? ACTION_UPDATE : ACTION_ADD this._items[key] = value - if (action === 'add') { + if (action === ACTION_ADD) { this._size++ } this._touch(action, key) @@ -144,7 +148,7 @@ export default class Collection extends EventEmitter { throw new IllegalTouch(value) } - this._touch('update', key) + this._touch(ACTION_UPDATE, key) return this.get(key) } @@ -155,7 +159,7 @@ export default class Collection extends EventEmitter { if (this.has(key)) { delete this._items[key] this._size-- - this._touch('remove', key) + this._touch(ACTION_REMOVE, key) } } @@ -164,7 +168,7 @@ export default class Collection extends EventEmitter { this._assertHas(key) this._items[key] = value - this._touch('update', key) + this._touch(ACTION_UPDATE, key) } // ----------------------------------------------------------------- @@ -344,17 +348,17 @@ export default class Collection extends EventEmitter { process.nextTick(flush) } - if (action === 'add') { - this._buffer[key] = this._buffer[key] ? 'update' : 'add' - } else if (action === 'remove') { - if (this._buffer[key] === 'add') { + if (action === ACTION_ADD) { + this._buffer[key] = this._buffer[key] ? ACTION_UPDATE : ACTION_ADD + } else if (action === ACTION_REMOVE) { + if (this._buffer[key] === ACTION_ADD) { delete this._buffer[key] } else { - this._buffer[key] = 'remove' + this._buffer[key] = ACTION_REMOVE } } else { // update if (!this._buffer[key]) { - this._buffer[key] = 'update' + this._buffer[key] = ACTION_UPDATE } } } diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index 78535713c..d3ea4d8b8 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -4,6 +4,11 @@ import callback from 'lodash.callback' import clearObject from './clear-object' import isEmpty from './is-empty' import NotImplemented from './not-implemented' +import { + ACTION_ADD, + ACTION_UPDATE, + ACTION_REMOVE +} from './collection' // =================================================================== @@ -53,15 +58,15 @@ export default class Index { // has not been emitted yet. this._onAdd(collection.all) - collection.on('add', this._onAdd) - collection.on('update', this._onUpdate) - collection.on('remove', this._onRemove) + collection.on(ACTION_ADD, this._onAdd) + collection.on(ACTION_UPDATE, this._onUpdate) + collection.on(ACTION_REMOVE, this._onRemove) } _detachCollection (collection) { - collection.removeListener('add', this._onAdd) - collection.removeListener('update', this._onUpdate) - collection.removeListener('remove', this._onRemove) + collection.removeListener(ACTION_ADD, this._onAdd) + collection.removeListener(ACTION_UPDATE, this._onUpdate) + collection.removeListener(ACTION_REMOVE, this._onRemove) clearObject(this._itemsByHash) clearObject(this._keysToHash) diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index 8a1d91b70..815e11990 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -3,6 +3,11 @@ import callback from 'lodash.callback' import clearObject from './clear-object' import NotImplemented from './not-implemented' +import { + ACTION_ADD, + ACTION_UPDATE, + ACTION_REMOVE +} from './collection' // =================================================================== @@ -42,15 +47,15 @@ export default class UniqueIndex { // has not been emitted yet. this._onAdd(collection.all) - collection.on('add', this._onAdd) - collection.on('update', this._onUpdate) - collection.on('remove', this._onRemove) + collection.on(ACTION_ADD, this._onAdd) + collection.on(ACTION_UPDATE, this._onUpdate) + collection.on(ACTION_REMOVE, this._onRemove) } _detachCollection (collection) { - collection.removeListener('add', this._onAdd) - collection.removeListener('update', this._onUpdate) - collection.removeListener('remove', this._onRemove) + collection.removeListener(ACTION_ADD, this._onAdd) + collection.removeListener(ACTION_UPDATE, this._onUpdate) + collection.removeListener(ACTION_REMOVE, this._onRemove) clearObject(this._itemByHash) clearObject(this._keysToHash) diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index b7c318b5c..be0b67871 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -2,7 +2,11 @@ import bind from 'lodash.bind' import createCallback from 'lodash.callback' import forEach from 'lodash.foreach' -import Collection from './collection' +import Collection, { + ACTION_ADD, + ACTION_UPDATE, + ACTION_REMOVE +} from './collection' // =================================================================== @@ -22,17 +26,17 @@ export default class View extends Collection { this._onRemove = bind(this._onRemove, this) // Register listeners. - this._collection.on('add', this._onAdd) - this._collection.on('update', this._onUpdate) - this._collection.on('remove', this._onRemove) + this._collection.on(ACTION_ADD, this._onAdd) + this._collection.on(ACTION_UPDATE, this._onUpdate) + this._collection.on(ACTION_REMOVE, this._onRemove) } // This method is necessary to free the memory of the view if its // life span is shorter than the collection. destroy () { - this._collection.removeListener('add', this._onAdd) - this._collection.removeListener('update', this._onUpdate) - this._collection.removeListener('remove', this._onRemove) + this._collection.removeListener(ACTION_ADD, this._onAdd) + this._collection.removeListener(ACTION_UPDATE, this._onUpdate) + this._collection.removeListener(ACTION_REMOVE, this._onRemove) } add () { From ce7bc9f438f27f95caecf1c0c4112eba340f72c4 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 2 Oct 2015 12:57:51 +0200 Subject: [PATCH 097/103] Correctly export isObject(). --- packages/xo-collection/src/is-object.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/src/is-object.js b/packages/xo-collection/src/is-object.js index 737694cb7..92961e81c 100644 --- a/packages/xo-collection/src/is-object.js +++ b/packages/xo-collection/src/is-object.js @@ -1,3 +1,3 @@ -export function isObject (value) { +export default function isObject (value) { return (value !== null) && (typeof value === 'object') } From 61c61adea1662d4a1bb219f648f90ddeb04e3379 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Thu, 21 Jan 2016 15:42:34 +0100 Subject: [PATCH 098/103] Minor code dedup. --- packages/xo-collection/src/collection.js | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 9875b4ff5..2a8290481 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -113,20 +113,14 @@ export default class Collection extends EventEmitter { } clear () { - forEach(this._items, (_, key) => { - delete this._items[key] - this._size-- - this._touch(ACTION_REMOVE, key) - }) + forEach(this._items, (_, key) => this._remove(key)) } remove (keyOrObjectWithId) { const [key] = this._resolveItem(keyOrObjectWithId) this._assertHas(key) - delete this._items[key] - this._size-- - this._touch(ACTION_REMOVE, key) + this._remove(key) } set (keyOrObjectWithId, valueIfKey = undefined) { @@ -157,9 +151,7 @@ export default class Collection extends EventEmitter { const [key] = this._resolveItem(keyOrObjectWithId) if (this.has(key)) { - delete this._items[key] - this._size-- - this._touch(ACTION_REMOVE, key) + this._remove(key) } } @@ -324,6 +316,12 @@ export default class Collection extends EventEmitter { return typeof key === 'number' || typeof key === 'string' } + _remove (key) { + delete this._items[key] + this._size-- + this._touch(ACTION_REMOVE) + } + _resolveItem (keyOrObjectWithId, valueIfKey = undefined) { if (valueIfKey !== undefined) { this._assertValidKey(keyOrObjectWithId) From 70e73a5a65e0ef49a95ab0080539f8884c31c5a3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 2 Nov 2016 15:00:04 +0100 Subject: [PATCH 099/103] fix(Collection#remove): properly report the key in related event --- packages/xo-collection/src/collection.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 2a8290481..60a507f1d 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -319,7 +319,7 @@ export default class Collection extends EventEmitter { _remove (key) { delete this._items[key] this._size-- - this._touch(ACTION_REMOVE) + this._touch(ACTION_REMOVE, key) } _resolveItem (keyOrObjectWithId, valueIfKey = undefined) { From 87daf0271c36f54a21f4056645bc6f4f7f1e4b37 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 2 Nov 2016 15:03:45 +0100 Subject: [PATCH 100/103] chore(package): update all dependencies --- packages/xo-collection/.babelrc | 15 ----- packages/xo-collection/.editorconfig | 2 +- packages/xo-collection/.gitignore | 7 +-- packages/xo-collection/.travis.yml | 11 ++-- packages/xo-collection/README.md | 19 +++--- packages/xo-collection/package.json | 59 +++++++++++++------ packages/xo-collection/src/collection.js | 2 +- packages/xo-collection/src/collection.spec.js | 2 +- packages/xo-collection/src/index.js | 5 +- packages/xo-collection/src/index.spec.js | 2 +- packages/xo-collection/src/unique-index.js | 5 +- .../xo-collection/src/unique-index.spec.js | 2 +- packages/xo-collection/src/view.example.js | 2 +- packages/xo-collection/src/view.js | 4 +- 14 files changed, 70 insertions(+), 67 deletions(-) delete mode 100644 packages/xo-collection/.babelrc diff --git a/packages/xo-collection/.babelrc b/packages/xo-collection/.babelrc deleted file mode 100644 index 5e9978a41..000000000 --- a/packages/xo-collection/.babelrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "comments": false, - "compact": true, - "optional": [ - // Experimental features. - // "minification.constantFolding", - // "minification.deadCodeElimination", - - "es7.asyncFunctions", - "es7.decorators", - "es7.exportExtensions", - "es7.functionBind", - "runtime" - ] -} diff --git a/packages/xo-collection/.editorconfig b/packages/xo-collection/.editorconfig index da21ef4c5..b6db0112a 100644 --- a/packages/xo-collection/.editorconfig +++ b/packages/xo-collection/.editorconfig @@ -41,7 +41,7 @@ indent_style = space # # Two spaces seems to be the standard most common style, at least in # Node.js (http://nodeguide.com/style.html#tabs-vs-spaces). -[*.js] +[*.{js,jsx,ts,tsx}] indent_size = 2 indent_style = space diff --git a/packages/xo-collection/.gitignore b/packages/xo-collection/.gitignore index 384949d8a..827e4e420 100644 --- a/packages/xo-collection/.gitignore +++ b/packages/xo-collection/.gitignore @@ -1,8 +1,7 @@ -/bower_components/ /dist/ +/node_modules/ npm-debug.log npm-debug.log.* - -!node_modules/* -node_modules/*/ +pnpm-debug.log +pnpm-debug.log.* diff --git a/packages/xo-collection/.travis.yml b/packages/xo-collection/.travis.yml index d38f7e60a..1a582c426 100644 --- a/packages/xo-collection/.travis.yml +++ b/packages/xo-collection/.travis.yml @@ -1,6 +1,9 @@ language: node_js node_js: - - 'iojs-v2' - - 'iojs-v1' - - '0.12' - - '0.10' + - stable + - 6 + - 4 + +# Use containers. +# http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +sudo: false diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 327af3662..7456895d4 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -232,24 +232,21 @@ const myView = new View(parentCollection, function predicate (value, key) { ## Development -### Installing dependencies - ``` +# Install dependencies > npm install -``` -### Compilation +# Run the tests +> npm test -The sources files are watched and automatically recompiled on changes. - -``` +# Continuously compile > npm run dev -``` -### Tests +# Continuously run the tests +> npm run dev-test -``` -> npm run test-dev +# Build for production (automatically called by npm install) +> npm run build ``` ## Contributions diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index f7f6a18f0..8a90f9336 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -21,44 +21,67 @@ "dist/", "*.js" ], + "engines": { + "node": ">=4" + }, "dependencies": { - "babel-runtime": "^5.6.11", + "babel-runtime": "^6.18.0", "kindof": "^2.0.0", - "lodash.bind": "^3.1.0", - "lodash.callback": "^3.3.0", - "lodash.foreach": "^3.0.3", + "lodash": "^3.10.1", "make-error": "^1.0.2" }, "devDependencies": { - "babel": "^5.6.11", - "babel-eslint": "^4.1.3", - "clarify": "^1.0.5", - "event-to-promise": "^0.3.2", - "ghooks": "^0.3.2", - "mocha": "^2.2.5", - "must": "^0.12.0", + "babel-cli": "^6.18.0", + "babel-eslint": "^7.1.0", + "babel-plugin-lodash": "^3.2.9", + "babel-plugin-transform-runtime": "^6.15.0", + "babel-preset-latest": "^6.16.0", + "babel-preset-stage-0": "^6.16.0", + "clarify": "^2.0.0", + "cross-env": "^3.1.3", + "dependency-check": "^2.6.0", + "event-to-promise": "^0.7.0", + "ghooks": "^1.3.2", + "mocha": "^3.1.2", + "must": "^0.13.2", + "rimraf": "^2.4.3", "sinon": "^1.14.1", - "source-map-support": "^0.3.2", - "standard": "^5.3.1", - "trace": "^1.2.0" + "source-map-support": "^0.4.6", + "standard": "^8.5.0", + "trace": "^2.3.3" }, "scripts": { - "build": "babel --source-maps --out-dir=dist/ src/", - "dev": "babel --watch --source-maps --out-dir=dist/ src/", + "build": "cross-env NODE_ENV=production babel --source-maps --out-dir=dist/ src/", + "clean": "rimraf dist/", + "depcheck": "dependency-check ./package.json --entry dist/collection.js index.js unique-index.js view.js", + "dev": "cross-env NODE_ENV=development babel --watch --source-maps --out-dir=dist/ src/", "lint": "standard", + "posttest": "npm run lint && npm run depcheck", + "prebuild": "npm run clean", + "predev": "npm run clean", "prepublish": "npm run build", "test": "npm run lint && mocha --opts .mocha.opts \"dist/**/*.spec.js\"", "test-dev": "mocha --opts .mocha.opts --watch --reporter=min \"dist/**/*.spec.js\"" }, + "babel": { + "plugins": [ + "lodash", + "transform-runtime" + ], + "presets": [ + "latest", + "stage-0" + ] + }, "standard": { "ignore": [ - "dist/**" + "dist" ], "parser": "babel-eslint" }, "config": { "ghooks": { - "pre-commit": "npm test" + "commit-msg": "npm test" } } } diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 60a507f1d..d65e8d7d6 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -1,7 +1,7 @@ -import forEach from 'lodash.foreach' import kindOf from 'kindof' import {BaseError} from 'make-error' import {EventEmitter} from 'events' +import {forEach} from 'lodash' import isEmpty from './is-empty' import isObject from './is-object' diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 773cb45d8..28c639a99 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -2,8 +2,8 @@ import eventToPromise from 'event-to-promise' import expect from 'must' -import forEach from 'lodash.foreach' import sinon from 'sinon' +import { forEach } from 'lodash' // =================================================================== diff --git a/packages/xo-collection/src/index.js b/packages/xo-collection/src/index.js index d3ea4d8b8..5c5dd01bc 100644 --- a/packages/xo-collection/src/index.js +++ b/packages/xo-collection/src/index.js @@ -1,5 +1,4 @@ -import bind from 'lodash.bind' -import callback from 'lodash.callback' +import { bind, iteratee } from 'lodash' import clearObject from './clear-object' import isEmpty from './is-empty' @@ -15,7 +14,7 @@ import { export default class Index { constructor (computeHash) { if (computeHash) { - this.computeHash = callback(computeHash) + this.computeHash = iteratee(computeHash) } this._itemsByHash = Object.create(null) diff --git a/packages/xo-collection/src/index.spec.js b/packages/xo-collection/src/index.spec.js index 298b13ea2..352708051 100644 --- a/packages/xo-collection/src/index.spec.js +++ b/packages/xo-collection/src/index.spec.js @@ -2,7 +2,7 @@ import eventToPromise from 'event-to-promise' import expect from 'must' -import forEach from 'lodash.foreach' +import { forEach } from 'lodash' // =================================================================== diff --git a/packages/xo-collection/src/unique-index.js b/packages/xo-collection/src/unique-index.js index 815e11990..45735b10b 100644 --- a/packages/xo-collection/src/unique-index.js +++ b/packages/xo-collection/src/unique-index.js @@ -1,5 +1,4 @@ -import bind from 'lodash.bind' -import callback from 'lodash.callback' +import { bind, iteratee } from 'lodash' import clearObject from './clear-object' import NotImplemented from './not-implemented' @@ -14,7 +13,7 @@ import { export default class UniqueIndex { constructor (computeHash) { if (computeHash) { - this.computeHash = callback(computeHash) + this.computeHash = iteratee(computeHash) } this._itemByHash = Object.create(null) diff --git a/packages/xo-collection/src/unique-index.spec.js b/packages/xo-collection/src/unique-index.spec.js index a7649362c..d972050b2 100644 --- a/packages/xo-collection/src/unique-index.spec.js +++ b/packages/xo-collection/src/unique-index.spec.js @@ -2,7 +2,7 @@ import eventToPromise from 'event-to-promise' import expect from 'must' -import forEach from 'lodash.foreach' +import { forEach } from 'lodash' // =================================================================== diff --git a/packages/xo-collection/src/view.example.js b/packages/xo-collection/src/view.example.js index f80ede21e..c7f546e60 100644 --- a/packages/xo-collection/src/view.example.js +++ b/packages/xo-collection/src/view.example.js @@ -1,4 +1,4 @@ -import forEach from 'lodash.foreach' +import { forEach } from 'lodash' import Collection from '..' import View from '../view' diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index be0b67871..7ef6fe952 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -1,6 +1,4 @@ -import bind from 'lodash.bind' -import createCallback from 'lodash.callback' -import forEach from 'lodash.foreach' +import { bind, forEach, iteratee as createCallback } from 'lodash' import Collection, { ACTION_ADD, From 32726efe8899492a6e1c1b99ccba8487d723cf74 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 2 Nov 2016 15:10:29 +0100 Subject: [PATCH 101/103] Revert "Temporary work around for eslint/eslint#3946." This reverts commit 63426818e6d43181ae635819fd1697fc9ea0a3d8. --- packages/xo-collection/src/view.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/xo-collection/src/view.js b/packages/xo-collection/src/view.js index 7ef6fe952..c0fe4741f 100644 --- a/packages/xo-collection/src/view.js +++ b/packages/xo-collection/src/view.js @@ -72,7 +72,7 @@ export default class View extends Collection { forEach(items, (value, key) => { if (predicate(value, key, this)) { super.set(key, value) - } else if (super.has(key)) { // eslint-disable-line space-before-keywords + } else if (super.has(key)) { super.remove(key) } }) @@ -80,7 +80,7 @@ export default class View extends Collection { _onRemove (items) { forEach(items, (value, key) => { - if (super.has(key)) { // eslint-disable-line space-before-keywords + if (super.has(key)) { super.remove(key) } }) From 9284aee3faa6859917e0f23ae4994e11da4d0262 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Wed, 2 Nov 2016 15:12:23 +0100 Subject: [PATCH 102/103] 0.4.1 --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index 8a90f9336..a3c1ee626 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -1,6 +1,6 @@ { "name": "xo-collection", - "version": "0.4.0", + "version": "0.4.1", "license": "ISC", "description": "Generic in-memory collection with events", "keywords": [], From 81b9348e50075f00974a9808f7ff599a56f025a4 Mon Sep 17 00:00:00 2001 From: "greenkeeper[bot]" Date: Mon, 28 Nov 2016 15:06:32 +0100 Subject: [PATCH 103/103] chore(package): update dependencies (#5) https://greenkeeper.io/ --- packages/xo-collection/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/xo-collection/package.json b/packages/xo-collection/package.json index a3c1ee626..987658be0 100644 --- a/packages/xo-collection/package.json +++ b/packages/xo-collection/package.json @@ -27,7 +27,7 @@ "dependencies": { "babel-runtime": "^6.18.0", "kindof": "^2.0.0", - "lodash": "^3.10.1", + "lodash": "^4.17.2", "make-error": "^1.0.2" }, "devDependencies": {