Categories
JavaScript Answers

How to Extract Elements with an Even Index from an Array?

Sometimes, we want to extract elements with an even index from an array.

In this article, we’ll look at how to extract elements with an even index from an array.

Extract Even Elements of an Array

To extract elements with an even index from an array., we can use the array filter instance method.

For instance, we can write:

const arr = [4, 5, 7, 8, 14, 45, 76];
const filtered = arr.filter((element, index) => {
  return (index % 2 === 0);
});
console.log(arr)

to call filter with a callback that has index as the 2nd parameter.

We return index % 2 === 0 to filter out all the elements that have odd indexes.

Therefore, filtered is [4, 5, 7, 8, 14, 45, 76] .

Conclusion

To extract elements with an even index from an array., we can use the array filter instance method.

Categories
JavaScript Answers

How to Add a Custom Button to the Toolbar that Calls a JavaScript Function with CKEditor?

Sometimes, we want to add a custom button to the toolbar that calls a JavaScript function with CKEditor.

In this article, we’ll look at how to add a custom button to the toolbar that calls a JavaScript function with CKEditor.

Add a Custom Button to the Toolbar that Calls a JavaScript Function with CKEditor

To add a custom button to the toolbar that calls a JavaScript function with CKEditor, we can add a command with the addCommand method.

Then we can add a method that calls the command with the addButton method.

For instance, we can add the editor with:

<script src="https://cdn.ckeditor.com/4.16.1/standard/ckeditor.js"></script>

<textarea id="container">How are you!</textarea>

Then we write:

const editor = CKEDITOR.replace('container');

editor.addCommand("mySimpleCommand", {
  exec(edt) {
    console.log(edt.getData());
  }
});

editor.ui.addButton('SuperButton', {
  label: "Click me",
  command: 'mySimpleCommand',
  toolbar: 'insert',
  icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'
});

to create the editor with:

const editor = CKEDITOR.replace('container');

Then we add a command with:

editor.addCommand("mySimpleCommand", {
  exec(edt) {
    console.log(edt.getData());
  }
});

The first argument is the name of the command.

The 2nd argument is an object with the exec method that has the code for the command.

We just call getData to get the input value of the text editor.

Next, we call ui.addButton with the button name the first argument.

Then 2nd argument has the settings for the button, which includes the command property set to the command that we want to run.

The icon is the URL for the icon.

Conclusion

To add a custom button to the toolbar that calls a JavaScript function with CKEditor, we can add a command with the addCommand method.

Then we can add a method that calls the command with the addButton method.

Categories
JavaScript Answers

How to Draw Lines in the HTML Canvas Without the Last Ones Being Faded?

Sometimes, we want to draw lines in the HTML canvas without the last ones being faded

In this article, we’ll look at how to draw lines in the HTML canvas without the last ones being faded.

Draw Lines in the HTML Canvas Without the Last Ones Being Faded

To draw lines in the HTML canvas without the last ones being faded, we can use the lineTo method and set the strokeStyle to the values we want.

For instance, we can create a canvas with:

<canvas id="myCanvas" width="400" height="400"></canvas>

Then we write:

const objCanvas = document.getElementById("myCanvas");
const objContext = objCanvas.getContext("2d");
const intGridWidth = 20;

const drawBackground = () => {
  objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);
  objContext.fillStyle = 'black';
  objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);
  objContext.strokeStyle = "white";
  for (let i = 1; i < objCanvas.width / intGridWidth; i++) {
    const x = Math.floor(i * intGridWidth) + 0.5;
    objContext.moveTo(x, 0);
    objContext.lineTo(x, objCanvas.height);
    objContext.stroke();
  }

  for (let i = 1; i < objCanvas.height / intGridWidth; i++) {
    const y = Math.floor(i * intGridWidth) + 0.5
    objContext.moveTo(0, y);
    objContext.lineTo(objCanvas.width, y);
    objContext.stroke();
  }

}
drawBackground();

to create the drawBackground function that clears the rectangle with:

objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);

Then we set the background to black with:

objContext.fillStyle = 'black';

Then we apply the background styles with:

objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);

Next, we set the line stroke style with:

objContext.strokeStyle = "white";

Next, we create the vertical grid lines with:

for (let i = 1; i < objCanvas.width / intGridWidth; i++) {
  const x = Math.floor(i * intGridWidth) + 0.5;
  objContext.moveTo(x, 0);
  objContext.lineTo(x, objCanvas.height);
  objContext.stroke();
}

We create the horizontal grid lines with:

for (let i = 1; i < objCanvas.height / intGridWidth; i++) {
  const y = Math.floor(i * intGridWidth) + 0.5
  objContext.moveTo(0, y);
  objContext.lineTo(objCanvas.width, y);
  objContext.stroke();
}

We use moveTo to move to the position we want to start drawing.

lineTo adds the line from the start and end position respectively.

stroke draws the line onto the canvas.

Conclusion

To draw lines in the HTML canvas without the last ones being faded, we can use the lineTo method and set the strokeStyle to the values we want.

Categories
JavaScript Answers

How to Convert a File Input Value to a Byte Array with JavaScript?

Sometimes, we want to convert a file input value to a byte array with JavaScript.

In this article, we’ll look at how to convert a file input value to a byte array with JavaScript.

Convert a File Input Value to a Byte Array with JavaScript

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

For instance, if we have the following HTML:

<input type='file'>

Then we can write:

const input = document.querySelector('input')
const reader = new FileReader();
const fileByteArray = [];

input.addEventListener('change', (e) => {
  reader.readAsArrayBuffer(e.target.files[0]);
  reader.onloadend = (evt) => {
    if (evt.target.readyState === FileReader.DONE) {
      const arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
      for (const a of array) {
        fileByteArray.push(a);
      }
      console.log(fileByteArray)
    }
  }
})

to get the input with document.querySelector .

Then we create a FileReader instance with:

const reader = new FileReader();

And we create a byte array with:

const fileByteArray = [];

Next, we call reader.readAsArrayBuffer in the file input’s change event listener to read the file into an array buffer.

Then we set the onloadend function to a function that runs when the file is loaded.

In the function, we get the buffer result with assign it to arrayBuffer .

Then we create the Uint8Array and assign it to array .

Finally, we push all the array entries into the fileByteArray .

Conclusion

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

Categories
JavaScript Answers

How to Stringify an ES6 Class Property with Getter or Setter into JSON?

Sometimes, we want to stringify an ES6class property with getter or setter into JSON.

In this article, we’ll look at how to stringify an ES6class property with getter or setter into JSON.

Stringify an ES6 Class Property with Getter or Setter into JSON

To stringify an ES6class property with getter or setter into JSON, we can add the toJSON method to the class to customize what to put in the JSON string.

For instance, we can write:

class MyClass {
  constructor(property) {
    this.property = property
  }

  set property(prop) {
    this._property = prop
  }

  get property() {
    return this._property
  }

  toJSON() {
    return {
      property: this.property
    }
  }
}

console.log(JSON.stringify(new MyClass('foo')))

to add the property property into the MyClass class.

We have the this.property instance property which is formed with getters and setters.

We just return an object with this.property set to the property property in toJSON to include.

Then when we create a new MyClass instance, we should see the this.property logged when we cal JSON.stringify on the MyClass instance.

Conclusion

To stringify an ES6class property with getter or setter into JSON, we can add the toJSON method to the class to customize what to put in the JSON string.