How much does it take to build a mobile application in Nepal in 2024?

Adit Malakar
January 4, 2024
8 minutes min read
Introduction In today’s digital era, People consider mobile phones as necessary as a wallet or handbag. Mobile applications have become integral to our daily lives, catering to various needs and enhancing convenience. Nepal’s mobile app development landscape has seen substantial growth and evolution over the years. With the increasing reliance on mobile devices, the demand […]

Introduction

In today’s digital era, People consider mobile phones as necessary as a wallet or handbag. Mobile applications have become integral to our daily lives, catering to various needs and enhancing convenience. Nepal’s mobile app development landscape has seen substantial growth and evolution over the years. With the increasing reliance on mobile devices, the demand for innovative and functional applications continues to surge.

Understanding Mobile App Development

Mobile app development creates applications specifically designed to run on mobile devices, such as smartphones or tablets. It involves software development, design, testing, and deployment to produce applications that cater to the functionalities and user experiences unique to mobile platforms.

Various aspects are involved in mobile app development:

Platform Selection: Developers choose the platforms for which they’ll create the app, such as iOS (Apple devices) or Android (Google devices). Sometimes, apps are developed for both platforms simultaneously (cross-platform development).

Coding and Programming: Developers use programming languages like Swift or Objective-C for iOS and Java or Kotlin for Android. Cross-platform frameworks like React Native, Flutter, or Xamarin are popular as they allow building apps for multiple platforms using a single codebase.

Design and User Interface (UI/UX): Designing an intuitive and visually appealing interface is crucial for user engagement. This involves creating wireframe mockups and then implementing the design into the app.

Testing: Thorough testing is essential to ensure the app functions appropriately on different devices and under various conditions. This includes functional testing, usability testing, performance testing, and more.

Deployment: Once the app is developed and tested, it’s submitted to the respective app stores (Apple App Store, Google Play Store, etc.), where users can download and install it on their devices.

Updates and Maintenance: Apps require continuous updates to fix bugs, introduce new features, and adapt to evolving technology or user needs. This ongoing maintenance is crucial for the app’s success.

Types of Mobile Applications:

Native mobile apps: For a specific operating system, like the IOS or Android phones, they’re designed to run on one platform and can be written in an individual programming language. Because they are created to work on a specific operating system or platform, native mobile apps are faster, more reliable, and capable of being offline.

HTML5 Mobile Apps: These apps allow you to benefit from the write-once-runanywhere method. HTML 5 is the most commonly used method for creating simple applications. It is highly effective and affordable to use cross-platform HTML5 mobile apps.

Hybrid Mobile Apps: These apps have native viewer functionality and back-end programming.

Some of the top apps in the world, including Gmail, Twitter, Amazon, and others, are hybrid applications. Hybrid apps can use plugins that give developers access to a platform’s native capabilities. They also develop more quickly and require less maintenance.

Mobile App Development Cost In Nepal

In Nepal, making mobile apps is quite a big deal right now, and people often wonder how it’s done and how much it costs. Developing an app can start at around Rs. 8,000 and go up from there, depending on the app’s needs.

First, making an app look good (UI/UX design) might cost about Rs. 8,000 for simple ones. But if you want it to look super fancy, that can be around Rs. 20,000. Then come the technical parts that make the app work behind the scenes (backend), which can bump the cost up to Rs. 40,000.

After building the app, checking and testing it (QA) to ensure it works well can add another Rs. 30,000 to the bill. Once it’s out there, maintaining and supporting the app could cost around Rs. 12,000 yearly. Plus, there are fees to put the app on the Appstore and Playstore – $99 for Appstore and $25 for Playstore.

If you’re thinking of making a specific app, like an online store (E-Commerce), that might cost around Rs. 1.5 lakh for both Android and iOS. Apps for things like food delivery or ones that are super easy to use might cost about Rs. 2.5 lakhs. Some popular apps like Pathao, Foodmandu, and Daraz started in these cost ranges and grew big over time.

The cool thing is, even though these costs give you a rough idea, they can change based on how complex the app is and what it needs. 

Here is an estimated price list of some of the apps you might consider developing:

Type of Mobile App Approximate CostDevelopment Time
Social Chat/Social Media App20 Lakh – 25 Lakh2-6 months
E-Learning App1 Lakh – 2.5 Lakh2-8 months
Fintech App1 Lakh – 2.5 Lakh2-6 months
Healthtech App1 Lakh – 2.5 Lakh2-6 months
Food Aggregator App2 Lakh – 4.5 Lakh1-4 months
Enterprise App1 Lakh – 2.5 Lakh3-8 months
Mobile Games2 Lakh – 4 Lakh2-7 months
Mobile Commerce App1 Lakh – 2.5 Lakh1-7 months
Media Streaming App50 Thousand – 1 Lakh1-6 months
Cab Booking App3 Lakh – 5.5 Lakh2-6 months
Multi-vendor e-commerce App50 Thousand – 5 Lakh2-6 months
E-Commerce App20 Thousand – 50 Thousand1 month
News Portal App20 Thousand – 50 Thousand1 month
Tourism Apps20 Thousand – 50 Thousand1 month
School College App20 Thousand – 50 Thousand1 month
Gold Silver Rate App10 Thousand – 50 Thousand1 month
Informative App20 Thousand – 30 Thousand1 month
Online TV/Radio App30 Thousand – 1 Lakh1 month

Conclusion

In conclusion, building a mobile application in Nepal in 2024 involves various factors contributing to the time and cost. From conceptualization to development and deployment, numerous elements impact the overall investment. Factors such as complexity, features, design, platform, and expertise play a pivotal role in determining the timeline and budget for your app project.

In these considerations, selecting the right development partner becomes crucial. This is where we at The Value Crew stand out. Our goal is simple: to offer more than just an app. We believe in creating experiences that exceed expectations. Our team is dedicated to delivering value that goes beyond numbers—it’s about crafting apps that resonate with users. We’re here to navigate the complexities of app development costs while ensuring you get the best value for your investment.

Head over to our website https://thevaluecrew.com/ and message us to get started. Email us at [email protected] or call us at +977-9843418300 to begin building your dream app. We are excited to get your project like it’s our project.

BACK TO BLOG

WordPress Debugging Guide (2023) – Part 1

Roshan Chapagain
February 11, 2023
7 minutes min read
Debugging is an essential part of the development process, and WordPress is no exception. Whether you're working on a custom plugin, theme, or website, you're bound to run into issues that need to be resolved. The first part of this blog series will explore the codex recommendation and WordPress functions for debugging. The second part will explore using third-party plugins and browser dev tools.

Debugging is an essential part of the development process, and WordPress is no exception. Whether you’re working on a custom plugin, theme, or website, you’re bound to run into issues that need to be resolved. The first part of this blog series will explore the codex recommendation and WordPress functions for debugging. The second part will explore using third-party plugins and browser dev tools; the series will cover everything you need to know to debug your WordPress projects effectively. Whether you’re a seasoned WordPress developer or just getting started, this guide will help you resolve issues and improve the performance of your WordPress website.

What does the Codex say?

WP_DEBUG

WP_DEBUG is a popular PHP constant that can be used to trigger the “debug” mode throughout WordPress.

define( 'WP_DEBUG_LOG', true );

-or-

define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );

Enabling WP_debug will cause all PHP errors, notices, and warnings to be displayed. This will modify the default behavior of PHP, which only displays errors and/or shows a white screen of death when errors are reached.

Php errors are shown after you enable WP_DEBUG.
Php errors are shown after you enable debugging using WP_DEBUG

WP_DEBUG_LOG

WP_DEBUG_LOG is a companion to WP_DEBUG that makes all errors saved to a debug.log file. All the generated notices on-screen and off (e.g., during an AJAX request or wp-cron run) can be found here.

Activating WP_DEBUG_LOG also gives access to PHP’s build-in error_log() function, which can be extremely useful, for instance, when debugging Ajax events. We will check this out in detail later.

Generally, when WP_DEBUG_LOG is set to true, the log is saved to debug.log in the content directory (wp-content/debug.log) within the site’s filesystem. Alternatively, we can set it to a valid file path to have the file saved elsewhere.

define( 'WP_DEBUG_LOG', true );

-or-

define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );

WP_DEBUG_DISPLAY

WP_DEBUG_DISPLAY works in conjunction with the WP_DEBUG constant. WP_DEBUG_DISPLAY controls whether the debug messages are shown in the front-end or stored in a log. The default ‘true’ value shows errors and warnings on the go, “false”  will remove all errors from the front-end and store them in a log, and can be reviewed later.

define( 'WP_DEBUG_DISPLAY', false );

SAVE_QUERIES

The SAVE_QUERIES definition saves the database queries to an array, and the array can be displayed to help analyze these queries. The constant defined as true causes each query to be saved, how long that query took to execute, and what function called it.

define( 'SAVEQUERIES', true );

The array is stored in the global $wpdb->queries.

We can use this code snippet to access it.

if (current_user_can('administrator')){

global $wpdb;

echo "<pre>";

print_r($wpdb->queries);

echo "</pre>";

}

SCRIPT_DEBUG

By default, WordPress loads minified versions of CSS and JS files in order to have a small impact on load times. This is great. But during development, it can be a pain if we are trying to work within one of the minified files to fix a bug or make improvements. SCRIPT_DEBUG can help us with this; setting it to true loads the un-minified versions of .js and .css files.

define( 'SCRIPT_DEBUG', true );

Function

error_log()

Note: Make sure debugging is turned on to use error_log()

If you want to log the errors without printing them in the front-end, add the following line:

define( 'WP_DEBUG_DISPLAY', false );

Sometimes when things are not working as expected. Logging and observing the data can definitely help. This is where the PHP function error_log() can help.

The error_log() function allows developers to log messages or errors to a file or the server error log. This can help identify and fix issues with a WordPress website. To use error_log(), include the function in your code and pass in the message or error you want to log as a string argument.

For example:

if ( !function_exists('some_function') ) {

error_log("Function some_function does not exist.");

}

In this example, the error message “Function some_function does not exist.” will be logged to the server error log if the function some_function is not found.

You can also pretty print your output by making use of the print_r method:

$array = array('item1', 'item2', 'item3');

error_log(print_r($array, true));

print_r()

This function prints the contents of a variable, such as an array or object, onto the screen. It’s a simple way to quickly see what’s inside a variable without digging through the logs.

$array = array('item1', 'item2', 'item3');

print_r($array, true);

var_dump()

This function displays structured information about variables, including their type and value. It’s useful for exploring the contents of arrays and objects, and it provides more detail than print_r().

Pro Tip:

If you cannot see the result, what you are trying to print or dump happens outside the page flow. You can stop the flow using die() function.

For example:

var_dump($types); // print_r($types);

die("products_first_ends");

That’s it for this one. Stay tuned for the second part, where we will discuss third-party plugins for debugging in detail.

BACK TO BLOG

Flutter CI/CD with Codemagic

Roshan Chapagain
February 28, 2021
6 minutes min read
Do you spend too much time deploying your Flutter app to the apple and android store instead of adding awesome features? Do you sometimes forget to deploy the app or just want a streamlined workflow you can set it up with Codemagic? Read on.

Codemagic allows you to easily integrate CI/CD for Flutter, essentially free. Their free plan provides a 500 minute build time each month. So, if you use them properly and efficiently the free plan will be enough.

What do you need?

  • A project hosted on Github, GitLab or Bitbucket
  • Google play console if you are planning to release your application in the Playstore

Let’s Go

1. Sign Up

You can easily signup with your Github, Bitbucket or Gitlab account.

I am signing up with my Bitbucket account.

Signup to Codemagic

After you have signed up. You see all the projects hosted by the provider associated with the account.

What if you do not see the project you are trying to use?

You can simply put the repository URL.  

You will have to provide the username and the password if you are accessing a Private repository.

And voilà.

Creating a workflow

Select Flutter App

Select Flutter App
Select Flutter App

Let us assume we are building a production workflow

The right menu is self-explanatory. What you might consider is naming your workflow for future use.

Naming your CI/CD Workflow
Naming Your Workflow

2. Build Triggers

Build triggers are as the name suggest, triggers that start the build.

You can set the build to start whenever:

  • You push to a specific branch
  • On pull request update
    • For this, you can specify whether each branch pattern matches the source or the target branch of the pull request
  • On tag creation

Here I am setting the build to start when I push to the production branch.

Setting up branch

Instead of entering the exact name of the branch, you can also use wildcard symbols to select more than one branch with one pattern.

Select “Show Pattern Examples” for how to.

Additional Patterns

3. Environment Variables

Environment Variables can be useful when you might have to pass a secret api key to your application or something similar.

Using Environment Variables

We are not going to be using any environment variables for the sake of this tutorial.

4. Dependency Caching

Codemagic allows storing dependency storing so you can speed up your builds.

PathDescription
$FLUTTER_ROOT/.pub-cacheDart cache
$HOME/.gradle/cachesGradle Cache
$HOME/Library/Caches/CocoaPodsCocoaPods Cache
Common Dependency Paths
Dependency Caching

For the Next Steps..

For the next three steps, Codemagic allows you to add a ‘Post script’ and ‘Pre Script’. ‘Post Script’ allows you to add scripts that are set to run before the particular phase and after the completion of the previous phase. Whereas, ‘Post script’ allows you to add scripts that are set to run after the particular phase has completed and before the next phase.

You can use these to do different things like:

  • Creating a directory and storing environment variables
  • Starting emulator beforehand and more
Post and Pre Scripts

5. Test

Codemagic runs your tests for you. It even does static code analysis with flutter analyze. You have to “Enable Flutter analyzer” for this.

Integration Testing

You can select one of the several options for running integration testing during the build.

  • Ios Simulator
  • Android Emulator
  • AWS Device Farm
Testing

6. Build

There are multiple settings that you can set before starting your build.

Build Section

You can change Flutter, Xcode and CocaPods version. You can also easily select what you are building your application for. And if you are building for android, the build format.

Build Mode

The build arguments allow you to do things like build versioning and choosing an alternate main file to run your project.

7. Publish

Publish

Codemagic allows easy publishing of all the generated artifacts to external services. Covering publishing thoroughly is a whole blog in itself. So we will only look onto the android sides of things for now.

For android publishing, the first thing you have to do is Android code signing. Find how to do that here.

Android Code Signing

Then, select Android Code Signing. Upload your keystore file, set keystore password, key alias and key password.

Add keystore

For publishing into Google Play. You have to upload a credentials.json. Find how to get it here. Set the appropriate track.  You can also set the Update Priority and Rollout Fraction within Codemagic.

Google Play Publishing

Congrats. You are done with setting CI/CD for flutter using Codemagic. You can manually start a build. By going to your Codemagic home page and clicking on Start new build, and choosing the appropriate branch and recently created workflow.

Starting Build
BACK TO BLOG

Serializers in Django REST Framework

Bibhuti Poudyal
January 10, 2021
1 minute min read
Serializers allow complex data like database query results and model instances to be converted to native Python data types which can then be easily rendered into JSON content types. It also provides deserialization, i.e. validating and then converting JSON data back into complex types. Multiple SeriaizerMethodField() needs to access the same resource in the Database. […]

Serializers allow complex data like database query results and model instances to be converted to native Python data types which can then be easily rendered into JSON content types. It also provides deserialization, i.e. validating and then converting JSON data back into complex types.

Multiple SeriaizerMethodField() needs to access the same resource in the Database. One easier way is to get the resource from DB at each get_<fieldname> method. It works fine but getting the same resource again and again from DB is not the performant solution. Instead, a “get_resource” function can be written to access the resource once and use it throughout the serializer. At each get_<fieldname> method existence of the resource is checked. If found it is used else the “get_resource” function is called.

Here, the ‘get_translation’ function gets the resource i.e. ‘translation’. Other methods ‘get_title’, ‘get_slug’ and ‘get_excerpt’ uses the method to the share common resource.

BACK TO BLOG

Shared custom response from Rails controller action

Bibhuti Poudyal
January 10, 2021
3 minutes min read
This post explains my recent experience regarding the endevour of implementing shared custom response from multiple controller actions in Ruby On Rails. Lets say we have a controller. Inside it lies the following actions: action_1, action_2, action_3 and action_4. All of these actions would respond with custom response and for convenience the responses will be in JSON format. We need […]

This post explains my recent experience regarding the endevour of implementing shared custom response from multiple controller actions in Ruby On Rails.

Lets say we have a controller. Inside it lies the following actions: action_1action_2action_3 and action_4. All of these actions would respond with custom response and for convenience the responses will be in JSON format. We need to send the same custom response from different actions, thus the response needs to be shared.

Such scenarios my arise when:

  • We need to validate some data before proceeding further.
  • The logic of the controller depends on the value of supplied params. If params is not present, controller needs to respond with respective message. etc…

The following text explains all the approaches which I tried for implementation of such requirements. And why one is better that the other.

Attempt 1

This approach uses a shared method to perform extra logic and provide a Boolean response which determines the action’s response. The logic is performed in res_n method and the response is returned from controller action.

As we can see, it has a lot of code duplication. The success response may be different but the error response need to be repeated in all actions. It violated the ruby’d DRY principle.

Attempt 2

This approach minimizes the code redundancy by moving the common error response to res_n methods. As you may have noticed the built-in method performed? is used. This method returns true if render method has already been invoked earlier. This way we prevent render method being called multiple times. The code is more simpler and cleaner than the first approach.

Attempt 3

This approach is the best among the previous two approaches. With a lot of research on code refactoring on this scenario I stumbled on this solution. It automatically prevents render method being called multiple times and make code more shorter, cleaner and easier than the 2nd approach. It uses built-in controller method before_action . This method gets called before each time a controller’s action is executed. The control of the program never enter the action method if it is returned from before_action method.

Conclusion

In this post, I have tried to explain the problem I faced during my ROR internship. And how I manged to solve it, trying different approaches, improving each time. Although the last attempt seems to be the best one, there may be scenarios where we need to implement the techniques of former approaches too.

BACK TO BLOG

Automate Vue Js deployment to AWS S3 bucket with CodeBuild

Bibhuti Poudyal
January 10, 2021
5 minutes min read
Deployment to your AWS S3 bucket can be a hassel. Automate this process with CodeBuild.

Prerequisites

  1. VueJS project on github
  2. Aws account

Steps

  • Create AWS bucket
  • Configure bucket for static hosting
  • Buildspec file
  • Create and configure code pipeline

Create AWS bucket

Create a bucket with your domain name.

Image for post

The bucket name must be unique.

Image for post

After the bucket is created; go to its detailed view. Click on the properties tab then select “Static website hosting”. Select the first option “Use this bucket to host a website”.

Image for post

Fill out the information as shown in the screenshot above and hit save.

As Vuejs is a single page application the error is also handled by index.html.

Configure bucket for static hosting

Next: the bucket needs to be accessed by other AWS services like CodeBuild, Lambda etc. For this purpose bucket policy needs to be configured.

Image for post

Under permissions goto “Bucket Policy” tab which contains a blank editor. Copy and paste the following configuration into it.

Replace the ARN under Resources with your bucket ARN.

ARN: Amazon Resource Name

Alternatively, beneath the editor click on the “Policy generator” link and generate the policy.

This finishes the S3 bucket setup.

Buildspec File

Before diving into the AWS CodePipeline, let’s talk about the buildspec file. Create a “buildspec.yml” file at the root of your Vuejs project and paste the following contents.

This section is just for understanding. Skip if you like.

Here you can see 4 phases:

install: Includes commands to run during installation. It installs/upgrades npm, pip and awscli required for further process.

pre_build: Commands to run before build. Install the dependencies by running npm install

build: command to build Vuejs project.

post_build: command to sync dist directory with S3 bucket. You need to change the build directory if the project has been built somewhere else. $S3_BUCKET is the ENVIRONMENT variable which we will configure later.

Create and configure AWS CodePipeline

It is the crucial step where we connect the GitHub repo with the S3 bucket and configure codepipeline for automatic deployment. At this step make sure you have pushed the latest changes to Github.

I have mentioned only Github here. As of now CodePipeline supports Github and BitBucket.

The pipeline for Vuejs project would be pretty simple; with two phases.

  1. Source: Gets the latest commit from Github’s appropriate branch
  2. Build: Install dependencies, build project and sync with S3

Navigate to AWS CodePipeline and click Create pipeline.

Image for post

At the create pipeline wizard, input pipeline name and service role.

Image for post

Expand the advanced tab.

Image for post

Artifact store: Custom location

Bucket: select the recently created bucket

Click Next

Image for post

Select GitHub. It may ask you to login and grant access. Then click connect.

Image for post

Select the appropriate Repository and branch. Leave GitHub Webhooks as default and click Next. Learn more about Github webhooks here.

Image for post

At “Add build stage”, select AWS Codebuild. Then click on “Create Project”. It will open a project creation wizard on a new window.

Image for post

On the Project creation form. Fill up the values as follows.

  • Project name: your project name
  • Environment image: Managed Image
  • Operating System: Ubuntu
  • Runtimes: Standard
  • Image: aws/codebuild/standard:4.0
  • Image version: Always use the latest image for this runtime version
  • Environment type: Linux
  • Service role: New service role

Expand the Additional configuration. Scroll to Environment variables. Insert S3_BUCKET on name field and name of the bucket on value field. That value will be used by the buildspec.yml file created earlier.

Image for post

Scroll and select “Use a buildspec file” on Buildspec section.

Image for post

Click Continue to Codepipeline. It will then close the window and return back to CodePipeline configurations with a success message.

Image for post

Skip the add deploy stage. Finally, review your configurations and click Create Pipeline.

Image for post

Now you should see the source and build stage being executed.

Image for post

In order to test the automatic deployment, push new commits to GitHub and wait for source and build phases to complete.

BACK TO BLOG

Snake game in 110 Lines of Code

Bibhuti Poudyal
January 10, 2021
8 minutes min read
Build a Snake game in 110 Lines of Code using just Html and JS.

In this article, I will build a simple snake game in JavaScript from scratch. The player can control the snake by the keyboard. Whenever the snake collides with food(a red circle), it gets 1 point and food moves to a random position.

You can view the finished application here. And the source code is here.

Image for post
Demo

The requirements for this application are basic knowledge of HTML, JavaScript, and some prior knowledge of HTML canvas.

The file structure of the application looks something like this:

  1. index.html: contains the HTML code
  2. script.js: contains the main logic of the application
Image for post
index.html file

The canvas is given the height and width of 500px and border-style ‘solid’ so we can view it clearly. It is given the id ‘canvas’ to reference it from script.js file That’s all for HTML. Open it in your browser and you will see an empty white box. That’s our canvas.

Now let’s move on to the scripting part. Initially, we get reference to the canvas so that we can draw on it.

Image for post
Reference canvas in HTML from JavaScript

In order to use canvas, we get reference to the context of the canvas. The parameter ‘2d’ is passed, which specifies that we are working in 2D. Next, we declare some variables which will hold our snake, food, score, direction, speed etc. Information of each variable is in the comments.

Image for post
Basic JavaScript setup for the game

Now we have our variables ready, we initialize our snake. Initially, snake array is empty. It’s supposed to contain the coordinates of the snake. Let’s do that now.

Image for post
Re-render the screen every 100 milliseconds

The for loop goes from 0 to length. Each time it adds a circle to the snake array so that the circle lies exactly to the left of the previous circle. For that, the x-coordinate of the circle is decreased each time by (size*2) and the y-coordinate is kept constant. After the snake is made ready we call the setInterval function which takes two parameters: a function to call each interval and an integer number which is the interval in milliseconds. In our case, it’s 100. i.e the function draw is called once in every 100 milliseconds.

The draw function is the main part of our program where the magic happens. In every 100 milliseconds, the draw function is invoked which clears the canvas, updates the position of the snake based on its direction, and redraws it. This happens so quickly that we don’t even notice. At the same time, it checks the collision of snake and food and updates the score too.

Image for post
the draw function

ctx.clearRect() method clears the canvas before redrawing. The successive for-loop loops over the circles of the snake from its tail to head (from the last index to the first index). If the current index is not the head, it sets it to its preceding circle. i.e. the last circle takes the position of second last circle, second last takes the position of third last, and so on… so that the snake seems as if it’s moving.

If the current index is head, first it checks the direction(at switch case) and increases the coordinate of the circle according to that direction.

Right: increase x-coordinate

Left: decrease x-coordinate

Up: decrease y-coordinate

Down: increase y-coordinate

After adding and subtracting the coordinate it should be drawn on the canvas so that the player can see the moving snake. The code below draws each circle of the snake with its updated coordinates.

Image for post
draw snakes with arc

Now the snake is drawn on the canvas. But it’s not the only thing to draw, we still need to draw the food and score. Drawing the food is similar to drawing the circles of the snake. In case of food, we fill it with red color. The next issue is checking the collision. The function checkCollission() does the job and returns a Boolean value. It takes two circles as its parameter, in our case, it’s the snake’s head and the food.

Image for post
Check for collision

The logic for the above function is quite simple. It what we studied in our school. First, we take the distance between the central points of two circles and compare it with the sum of their radii. If it is greater: no collision; else: they collided. The illustration will clear the concept.

Image for post
check distance between centers of two circles to detect collision

If checkCollission() returns true, first the score is increased and the food is placed on any random position between 0 to width/height of the canvas. The random function takes two parameter min, max, and gives a random number between them.

Image for post
random function

Now we have come to the end. The last piece of the puzzle is the keydown event handler. We need to control the direction of the snake according to the keyboard button pressed.

Image for post
handle keyboard events

The onkeydown handler is invoked whenever a key is pressed down. Then we check if the key is rightleftup or down arrow and assign the respective direction. 373839 and 40 are the keyCode (ASCII value) for left, up, right and down arrows. Now save the file and open it in your browser.

The code doesn’t work yet. It’s because, for the code to work the timer should start, which we haven’t done yet. As you have noticed, the timer is set in init() function. So call the init function at the last line of your code, save it, and refresh the browser. You can see a moving snake that you can control with the keyboard’s arrow keys.

Happy Coding !

BACK TO BLOG

Migrate vue-i18n to poeditor

Bibhuti Poudyal
January 10, 2021
5 minutes min read
Internationalization is a basic feature for web apps having users from different corners of the world. vue-i18n makes the process very smooth to implement internationalization into VueJs web apps. Poeditor is another tool that provides a smooth translation workflow.

Internationalization is a basic feature for web apps having users from different corners of the world. vue-i18n makes the process very smooth to implement internationalization into VueJs web apps. Poeditor is another tool that provides a smooth translation workflow.

Recently I ‘d a chance to migrate the Vue application (with local translation data) to make it work with Poeditor’s API.

In case you don’t know about poeditor. It provides a smooth translation workflow. And also

  • Translators can manage your translations
  • It gives simple REST API to access the data

For more details visit poeditor.

The technique mentioned in this article works for this particular scenario:

  • You already have translation working from local translation files
  • You don’t want to change any of the current workflow
  • You want to take advantage of all the cool features of poeditor

This article suggests an architecture that perfectly fulfills the above requirements.

Vue.js + Node.js Proxy + Poeditor API

The first step would be to import the existing vue-i18n’s JSON translation file to poeditor.

Import current translation to poedditor

As you may have noticed, the import process flattens the nested JSON object. If your translation data is only 1 level deep, this shouldn’t be an issue. In case of nested data, note the context below translation terms. It will be used later to gain the original nested structure.

Now lets look at the changes in Vue application. This solution is a derived version of vue-i18n’s Lazy Loading guide.

This is how default i18n file looks like, before the change.

The current structure needs to be changed in order to fetch data from the API. And it needs to export two things

  • the i18n instance
  • loadLanguageAsync function

The loadLanguageAsync function loads translation data from the server and sets the data and locale accordingly. setI18nLanguage sets i18n’s locale and updates lang attribute of html tag with new translation. silentTranslationWarn property enables/disables console warnings.

i18n.js file after the required changes:

When we have the functions ready we need to decide a best place to call the function. If your language depends on the URL, you should probably follow the vue-i18n’s Lazy loading guide; it asynchronously loads the translation before each route change according to route params.

For our case, we need to get the translation only once when the app loads. So App.vue seems to be the best place to call this function.

Image for post
at App.vue

Inside the created function new translations are loaded. The loading computed property tells whether the translation has been loaded or not. You can use this property to show loading message until the translation loads.

Image for post

Usage of loading computed property at App.vue

That should take care of everything on the front end.

Backend Proxy

For back-end I have chosen NodeJS and Express as it allows to create API very quickly.

The server will be responsible for:

  • Request data from poeditor
  • Format locale data to match vue-i18n structure

The reason for using proxy: Poeditor REST API is protected with CORS. So it doesn’t allow frontend application to request data. Moreover, the data needs to be formatted which can be an overhead on the browser. Formatting on the server is faster and it can be cached too.

The main server.js file contains the logic to fetch data from poeditor API inside /translations route.

Image for post
server.js

The logic to format the data is inside /helpers/poeditor.js file. It makes use of loadash to construct nested objects out of flattened data. If your data is already flat, it will give the output accordingly.

As mentioned earlier, to format the data into its original structure it makes use of ‘content’ property from poeditor’s API response.

Image for post
/helpers/poeditor.js

All of these setup should be enough. Now spin up the NodeJS and vue development server, it will work like magic.

The beautiful code snippets for this article are generated using RamroCode.

BACK TO BLOG

Multiple usage of custom filters in Vue.js

Bibhuti Poudyal
January 10, 2021
2 minutes min read
Learn to use custom filters in Vue.js. Vue.js allows you to define filters that can be used to apply common text formatting.

A Vue.js filter is simply a function that takes an input, processes it and gives an output. Inside a Vue template, it is written after a single pipe and can also be followed by its arguments.

Example of Vue.js filter

But there can be some particular case where the filter functions are required to be used outside directive and mustaches. This article will show a simple mechanism to tackle the problem.

A custom filter can be registered either globally or inside components. Since we are doing it the best way, we will be registering it globally.

If you have many filters, its best to keep it on a separate folder inside separate files. For this particular case, I have kept it inside /src/filters.js

Place filters.js inside ‘src’

Now lets take a look inside filters.js file.

filter.js

As you may have noticed, the FILTERS object contains all of your filter functions. The key serves as filterId and the value as filter function

The file exports two things

  • FILTERS object
  • registerFilters function

That’s the main point. The registerFilters function registers all of the filter functions globally so that it can be used on any Vue component. The method is called inside the main.js file.

Inside main.js

Another cool thing about this approach is the ability to import those filter functions and use inside JavaScript logic.

Inside JavaScript logic of XXX.vue component

In many cases filter functions need to be used outside of directive and mustaches. This approach works best to handle this particular scenario. Moreover, it groups the filter functions at one place and makes a clear separation of logic inside vue application.

Like the code snippets used in this article. It’s generated using this awesome tool RamroCode 👌

Happy Coding !