This will sort your array by "one" and if they are the same (ie. 0) then it will sort by "two". It's simple, concise, readable, and best of all - works perfectly.
// arr[5][2]
var arr = new Array(5);
for (var i = 0; i < arr.length; i++) {
arr[i] = new Array(2);
}
2차원 배열 생성 함수를 만들어서 사용
function create2DArray(rows, columns) {
var arr = new Array(rows);
for (var i = 0; i < rows; i++) {
arr[i] = new Array(columns);
}
return arr;
}
// arr[5][2]
var arr = create2DArray(5, 2);
Array 객체에 배열 생성 함수를 추가하여 사용
Array.matrix = function (m, n, initial) {
var a, i, j, mat = [];
for (i = 0; i < m; i += 1) {
a = [];
for (j = 0; j < n; j += 1) {
a[j] = initial;
}
mat[i] = a;
}
return mat;
};
// matrix('행', '열', '기본값')
var arr = Array.matrix(5, 2, 0);
In this article, we cover breakdown Bubble Sort and then also share its implementation in Javascript.
Firstly, let's get it out of the way. When we say "sort", the idea is to re-arrange the elements such that they are in ascending order.
If you are new to the concept of sorting, each section of the article would be useful - concept of bubble sort, its algorithms, efficiency, etc. However, If you are here to refresh your knowledge, jump straight to the javascript implementation of the sort.Go to code
If you are a newbie to sorting, Bubble sort is a great place to start! It is one of the more intuitive sorting methods as its algorithm mirrors how our brain generally thinks about sorting - by comparing.
Let's remove the vagueness and delve deeper into it.
A. What Bubble Sort Does?
To achieve sorting in Bubble Sort, the adjacent elements in the array are compared and the positions are swapped if the first element is greater than the second. In this fashion, the largest value "bubbles" to the top.
Usually, after each iteration the elements furthest to the right are in correct order. The process is repeated until all the elements are in their right position.
B. What Bubble Sort Does?
1. Starting with the first element, compare the current element with the next element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, just move to the next element.
As you might have noticed, Bubble Sort only considers one element at a time. Thus, it is highly time consuming and inefficient. Due to its inefficiency, bubble sort is almost never used in production code.
You can use a built in function Array.prototype.sort() for sorting. This is an inplace algorithm just like bubble sort which converts the elements of the input array into strings and compares them based on their UTF-16 code unit values. Also, if you are interested, you can read about index sort which is another simple comparison based sort method that has a better performance than Bubble sort.
Implementing Bubble Sort using Javascript
Now as we have seen the logic behind bubble sort, we can write the code for it in a straightforward manner, using two nested loops.
let bubbleSort = (inputArr) => {
let len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (inputArr[j] > inputArr[j + 1]) {
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
}
return inputArr;
};
As you can see here, the sorting function will run until the variable "i" is equal to the length of the array. This might not be the most efficient solution as it means the function will run on an already sorted array more than once.
A slightly better solution involves tracking a variable called "checked" which is initially set to FALSE and becomes true when there is a swap during the iteration. Running this code on a do while loop to run the sorting function only when "checked" is true ensures that the function will not run on a sorted array more than once.
let bubbleSort = (inputArr) => {
let len = inputArr.length;
let checked;
do {
checked = false;
for (let i = 0; i < len; i++) {
if (inputArr[i] > inputArr[i + 1]) {
let tmp = inputArr[i];
inputArr[i] = inputArr[i + 1];
inputArr[i + 1] = tmp;
checked = true;
}
}
} while (checked);
return inputArr;
};
Want to create a plugin to extend WooCommerce? WooCommerce plugins are the same as regular WordPress plugins. For more information, visitWriting a plugin.
Your WooCommerce extension should:
Adhere to all WordPress plugin coding standards, as well asbest practice guidelinesfor harmonious existence within WordPress and alongside other WordPress plugins.
Have a single core purpose and use WooCommerce features as much as possible.
Not do anything malicious or underhanded — for example, inserting spam links or up selling services outside of the WooCommerce.com ecosystem.
Not subvert or override Marketplace connections in core — for example, extensions cannot create branded top level menu items or introduce their own telemetry.
Merchants make use of WooCommerce extensions daily, and should have an unified and pleasant experience while doing so without advertising invading their WP Admin or store.
Note: We provide this page as a best practice for developers.
Note:We are unable to provide support for custom code under ourSupport Policy. If you are unfamiliar with code and resolving potential conflicts, select aWooExpert or Developer for assistance.
Check if WooCommerce is active
Most WooCommerce plugins do not need to run unless WooCommerce is already active. You can wrap your plugin in a check to see if WooCommerce is installed:
/** * Check if WooCommerce is active **/ if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) { // Put your plugin code here }
Note that this check will fail if the WC plugin folder is named anything other thanwoocommerce.
Main file naming
The main plugin file should adopt the name of the plugin, e.g., A plugin with the directory nameplugin-namewould have its main file namedplugin-name.php.
Text domains
Follow guidelines forInternationalization for WordPress Developers, the text domain should match your plugin directory name, e.g., A plugin with a directory name ofplugin-namewould have the text domainplugin-name. Do not use underscores.
Localization
All text strings within the plugin code should be inEnglish. This is the WordPress default locale, and English should always be the first language. If your plugin is intended for a specific market (e.g., Spain or Italy), include appropriate translation files for those languages within your plugin package. Learn more at Using Makepot to translate your plugin.
Follow WordPress PHP Guidelines
WordPress has aset of guidelinesto keep all WordPress code consistent and easy to read. This includes quotes, indentation, brace style, shorthand php tags, yoda conditions, naming conventions, and more. Please review the guidelines.
=== Plugin Name === Contributors: (this should be a list of wordpress.org userid's) Tags: comments, spam Requires at least: 4.0.1 Tested up to: 4.3 Requires PHP: 5.6 Stable tag: 4.3 License: GPLv3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html
Plugin Author Name
Consistency is important to us and our customers. Products offered through WooCommerce.com should provide a consistent experience for all aspects of the product, including finding information on who to contact with queries.
Customers should be able to easily to differentiate a product purchased at WooCommerce.com from a product purchased elsewhere, just by looking through their plugin list in WordPress.
Thus, the following plugin headers should be in place:
ThePlugin AuthorisYourName/YourCompany
TheDeveloperheader is YourName/YourCompany, with theDeveloper URIfield listed ashttp://yourdomain.com/
For example:
/** * Plugin Name: WooCommerce Extension * Plugin URI: http://woocommerce.com/products/woocommerce-extension/ * Description: Your extension's description text. * Version: 1.0.0 * Author: Your Name * Author URI: http://yourdomain.com/ * Developer: Your Name * Developer URI: http://yourdomain.com/ * Text Domain: woocommerce-extension * Domain Path: /languages * * Woo: 12345:342928dfsfhsf8429842374wdf4234sfd * WC requires at least: 2.2 * WC tested up to: 2.3 * * License: GNU General Public License v3.0 * License URI: http://www.gnu.org/licenses/gpl-3.0.html */
Declaring required and supported WooCommerce version
Use the follow headers to declare “required” and “tested up to” versions:
WC requires at least
WC tested up to
Plugin URI
Ensure that thePlugin URIline of the above plugin header is provided. This line should contain the URL of the plugin’s product/sale page on WooCommerce.com (if sold by WooCommerce) or to a dedicated page for the plugin on your website.
Woo Plugin Header For Updates
WooCommerce core looks for aWooline in the plugin header comment, to ensure it can check for updates to your plugin, on WooCommerce.com. This line looks like this:
Woo: 12345:342928dfsfhsf8429842374wdf4234sfd
This isonly required for products sold on WooCommerce.com. Using this line for products listed on WordPress.org or elsewhere is not required or necessary.
For products sold on WooCommerce.com, Vendors can find this snippet by logging in to their logging in to the Vendors Dashboard and going toExtensions > All Extensions. Then, selectthe product and clickEdit product page. This snippet will be in the upper-right-hand corner of the screen.
See the plugin header comment example above for how theWooheader looks in context.
Make it Extensible
Developers should use WordPress actions and filters to allow for modification/customization without requiring users to touch the plugin’s core code base.
If your plugin creates a front-end output, we recommend to having a templating engine in place so users can create custom template files in their theme’s WooCommerce folder to overwrite the plugin’s template files.
With version control, there’s no reason to leave commented-out code; it’s annoying to scroll through and read. Remove it and add it back later if needed.
Comment
If you have a function, what does the function do? There should be comments for most if not all functions in your code. Someone/You may want to modify the plugin, and comments are helpful for that. We recommend usingPHP Doc Blocks similar toWooCommerce.
Avoid God Objects
God Objectsare objects that know or do too much. The point of object-oriented programming is to take a large problem and break it into smaller parts. When functions do too much, it’s hard to follow their logic, making bugs harder to fix. Instead of having massive functions, break them down into smaller pieces.
Test Your Code with WP_DEBUG
Always develop withWP_DEBUGmode on, so you can see all PHP warnings sent to the screen. This will flag things like making sure a variable is set before checking the value.
Separate Business Logic & Presentation Logic
It’s a good practice to separate business logic (i.e., how the plugin works) frompresentation logic(i.e., how it looks). Two separate pieces of logic are more easily maintained and swapped if necessary. An example is to have two different classes — one for displaying the end results, and one for the admin settings page.
Use Transients to Store Offsite Information
If you provide a service via an API, it’s best to store that information so future queries can be done faster and the load on your service is lessened.WordPress transients can be used to store data for a certain amount of time.
Logging Data
You may want to log data that can be useful for debugging purposes. This is great with two conditions:
Allow any logging as an ‘opt in’.
Use theWC_Loggerclass. A user can then view logs on their system status page.
If adding logging to your extension, here’s a snippet for presenting a link to the logs, in a way the extension user can easily make use of.
This information is intended for the third-party developers so products they write can better handle errors. Error codes are produced by the Product Build Server when uploading a new submission or updating an existing product on the Marketplace.
error_success
The operation has completed successfully.
error_pbs_prepare_apache
Internal error with the Product Build Server – cannot initialize the Apache daemon.
error_pbs_prepare_mysql
Internal error with the Product Build Server – cannot initialize the MySQL daemon.
error_pbs_prepare_wp
Internal error with the Product Build Server – cannot initialize WordPress.
error_pbs_prepare_wc
Internal error with the Product Build Server – cannot initialize WooCommerce.
error_pbs_prepare_dependencies
Internal error with the Product Build Server – cannot configure dependencies.
error_pbs_test_malware_scanning
Malware scanning error. This can happen if your product contains malware in the code.
This means that the character at the absolute position 0x406 (1030) and 0x506 (1286) in the filehtml-settings-page.phpdoesn’t pass the$ini_setrule, because it is usingcall_user_funcin that file. Also, the other filehtml-extras-page.phpdoesn’t pass the rule$register_functionwhich is usingexeccall.
error_pbs_test_extracting
Cannot extract the product. Most common issue is the top directory of the zip does not match its slug.
error_pbs_test_phpcs
phpcschecks failed. The check uses theWooCommerce-Coresniffs with followingphpcs.xml:
Cannot install the product. Most common issue is the top directory of the zip does not match its slug.
error_pbs_test_activating
Cannot activate the product. Refer to the build output for more details.
error_pbs_test_deactivating
Cannot deactivate the product. Refer to the build output for more details.
error_pbs_test_host_plan_installing
This error means that your product is incompatible with other products in the host plan. Refer to the build output for more details.
error_pbs_test_host_plan_activating
This error means that your product is incompatible with other products in the host plan. Refer to the build output for more details.
error_pbs_test_host_plan_deactivating
This error means that your product is incompatible with other products in the host plan. Refer to the build output for more details.
error_pbs_missing_theme_info_file
Your theme is missing the theme info filetheme_info.txtunder the root directory.
error_pbs_incomplete_theme_info
Your theme info filetheme_info.txtcontains malformed data structure. It should contain the product ID, hash and main file, all separated by new lines. For example: