728x90

The Uint8Array typed array represents an array of 8-bit unsigned integers. The contents are initialized to 0. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).

Constructor

Uint8Array()Creates a new Uint8Array object.

Static properties

Uint8Array.BYTES_PER_ELEMENTReturns a number value of the element size. 1 in the case of an Uint8Array.Uint8Array.nameReturns the string value of the constructor name. In the case of the Uint8Array type: "Uint8Array".

Static methods

Uint8Array.from()Creates a new Uint8Array from an array-like or iterable object. See also Array.from().Uint8Array.of()Creates a new Uint8Array with a variable number of arguments. See also Array.of().

Instance properties

Uint8Array.prototype.bufferReturns the ArrayBuffer referenced by the Uint8Array. Fixed at construction time and thus read only.Uint8Array.prototype.byteLengthReturns the length (in bytes) of the Uint8Array. Fixed at construction time and thus read only.Uint8Array.prototype.byteOffsetReturns the offset (in bytes) of the Uint8Array from the start of its ArrayBuffer. Fixed at construction time and thus read only.Uint8Array.prototype.lengthReturns the number of elements held in the Uint8Array. Fixed at construction time and thus read only.

Instance methods

Uint8Array.prototype.copyWithin()Copies a sequence of array elements within the array. See also Array.prototype.copyWithin().Uint8Array.prototype.entries()Returns a new array iterator object that contains the key/value pairs for each index in the array. See also Array.prototype.entries().Uint8Array.prototype.every()Tests whether all elements in the array pass the test provided by a function. See also Array.prototype.every().Uint8Array.prototype.fill()Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill().Uint8Array.prototype.filter()Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter().Uint8Array.prototype.find()Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find().Uint8Array.prototype.findIndex()Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex().Uint8Array.prototype.forEach()Calls a function for each element in the array. See also Array.prototype.forEach().Uint8Array.prototype.includes()Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes().Uint8Array.prototype.indexOf()Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf().Uint8Array.prototype.join()Joins all elements of an array into a string. See also Array.prototype.join().Uint8Array.prototype.keys()Returns a new array iterator that contains the keys for each index in the array. See also Array.prototype.keys().Uint8Array.prototype.lastIndexOf()Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.lastIndexOf().Uint8Array.prototype.map()Creates a new array with the results of calling a provided function on every element in this array. See also Array.prototype.map().Uint8Array.prototype.reduce()Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also Array.prototype.reduce().Uint8Array.prototype.reduceRight()Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also Array.prototype.reduceRight().Uint8Array.prototype.reverse()Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also Array.prototype.reverse().Uint8Array.prototype.set()Stores multiple values in the typed array, reading input values from a specified array.Uint8Array.prototype.slice()Extracts a section of an array and returns a new array. See also Array.prototype.slice().Uint8Array.prototype.some()Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some().Uint8Array.prototype.sort()Sorts the elements of an array in place and returns the array. See also Array.prototype.sort().Uint8Array.prototype.subarray()Returns a new Uint8Array from the given start and end element index.Uint8Array.prototype.values()Returns a new array iterator object that contains the values for each index in the array. See also Array.prototype.values().Uint8Array.prototype.toLocaleString()Returns a localized string representing the array and its elements. See also Array.prototype.toLocaleString().Uint8Array.prototype.toString()Returns a string representing the array and its elements. See also Array.prototype.toString().Uint8Array.prototype[@@iterator]()Returns a new array iterator object that contains the values for each index in the array.

Examples

Different ways to create a Uint8Array

// From a length var uint8 = new Uint8Array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2 console.log(uint8.BYTES_PER_ELEMENT); // 1 // From an array var arr = new Uint8Array([21,31]); console.log(arr[1]); // 31 // From another TypedArray var x = new Uint8Array([21, 31]); var y = new Uint8Array(x); console.log(y[0]); // 21 // From an ArrayBuffer var buffer = new ArrayBuffer(8); var z = new Uint8Array(buffer, 1, 4); // From an iterable var iterable = function*(){ yield* [1,2,3]; }(); var uint8 = new Uint8Array(iterable); // Uint8Array[1, 2, 3]

Specifications

Specification

ECMAScript (ECMA-262)
The definition of 'TypedArray constructors' in that specification.

Browser compatibility

 

 

developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array

728x90

View: gettimeofday

Function:
Description: Returns the current time as array.

Code

function gettimeofday (return_float) {
    // http://jsphp.co/jsphp/fn/view/gettimeofday
    // + original by: Brett Zamir (http://brett-zamir.me)
    // +      derived from: Josh Fraser (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/)
    // +         parts by: Breaking Par Consulting Inc (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7)
    // +  revised by: Theriault
    // *   example 1: gettimeofday();
    // *   returns 1: {sec: 12, usec: 153000, minuteswest: -480, dsttime: 0}
    // *   example 1: gettimeofday(true);
    // *   returns 1: 1238748978.49
    var t = new Date(),
        y = 0;

    if (return_float) {
        return t.getTime() / 1000;
    }

    y = t.getFullYear(); // Store current year.
    return {
        sec: t.getUTCSeconds(),
        usec: t.getUTCMilliseconds() * 1000,
        minuteswest: t.getTimezoneOffset(),
        // Compare Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC to see if DST is observed.
        dsttime: 0 + (((new Date(y, 0)) - Date.UTC(y, 0)) !== ((new Date(y, 6)) - Date.UTC(y, 6)))
    };
}
728x90

What is the best way(s) to fake function overloading in Javascript?

I know it is not possible to overload functions in Javascript as in other languages. If I needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way:

  1. Using different names in the first place
  2. Using optional arguments like y = y || 'default'
  3. Using number of arguments
  4. Checking types of arguments
  5. Or how?

javascriptoverloading

share  improve this question  follow 

edited Jul 2 '15 at 7:47

Sergey Maksimenko

5606 silver badges20 bronze badges

asked Jan 19 '09 at 0:06

hamdiakoguz

13.6k9 gold badges30 silver badges27 bronze badges

  • 16

    Perhaps it would be useful to ask why you think you need function overloading to begin with. I think that will get us closer to a real solution. – Breton Jan 19 '09 at 0:41

  • 1

    This is closed, but I do the following: this.selectBy = { instance: selectByInstance, // Function text: selectByText, // Function value: selectByValue // Function }; – Prisoner ZERO Jun 22 '12 at 20:46

  •  

    My answer shows how to do run time function overloading, it has a speed penalty and I wouldn't advise doing it to get around Javascript's specification. Function overloading is really a compile time task, I only provide the answer for academic purposes and leave it up to your own discretion as to whether or not to employ it in code. – Keldon Alleyne Oct 23 '12 at 22:57

  • 2

    Just in case it is useful, I've built a lightweight js framework that allows for type-based method overloading. Obviously the same caveats apply with regards to performance, but it's worked well for my needs so far and still has quite a lot of room for improvement: blog.pebbl.co.uk/2013/01/describejs.html#methodoverloading – Pebbl Jan 15 '13 at 0:24

add a comment

37 Answers

ActiveOldestVotes

1

2Next

626

 

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

 

 

function foo(a, b, opts) {
  // ...
  if (opts['test']) { } //if test param exists, do something.. 
}


foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});

 

 

 

179

I often do this:

C#:

public string CatStrings(string p1)                  {return p1;}
public string CatStrings(string p1, int p2)          {return p1+p2.ToString();}
public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}

CatStrings("one");        // result = one
CatStrings("one",2);      // result = one2
CatStrings("one",2,true); // result = one2true

JavaScript Equivalent:

function CatStrings(p1, p2, p3)
{
  var s = p1;
  if(typeof p2 !== "undefined") {s += p2;}
  if(typeof p3 !== "undefined") {s += p3;}
  return s;
};

CatStrings("one");        // result = one
CatStrings("one",2);      // result = one2
CatStrings("one",2,true); // result = one2true

his particular example is actually more elegant in javascript than C#. Parameters which are not specified are 'undefined' in javascript, which evaluates to false in an if statement. However, the function definition does not convey the information that p2 and p3 are optional. If you need a lot of overloading, jQuery has decided to use an object as the parameter, for example, jQuery.ajax(options). I agree with them that this is the most powerful and clearly documentable approach to overloading, but I rarely need more than one or two quick optional parameters.

EDIT: changed IF test per Ian's suggestion

share  improve this answer  follow 

edited Jul 2 '15 at 17:11

 

answered Feb 15 '12 at 17:19

rocketsarefast

3,6941 gold badge18 silver badges18 bronze badges

  • 17

    Parameters which are not specified are undefined in JS, not null. As a best practice, you should never set anything to undefined, so it should not be a problem as long as you change your test to p2 === undefined. – Tamzin Blake Aug 31 '12 at 17:49

  • 3

    If you pass false as the last argument then it won't concatenate "false" to the end, because the if(p3) won't branch. – dreamlax Oct 23 '12 at 5:50

  • 6

    Just a quick note, your typeof p2 === "undefined" is probably the reverse of what you're expecting in the instance of your example, I think typeof p2 !== "undefined" is what you intended. Also, May I suggest being its supposed to concatenate string, number, and boolean that you actually do p2 === "number"; p3 === "boolean" – WillFM Apr 23 '13 at 2:56 

  • 8

    I like doing this: p3 = p3 || 'default value'; – Dorian Jun 17 '14 at 15:46 

  • 3

    What is the meaning of === and !==? Why not just use == and !=? – Ricardo Cruz Mar 2 '16 at 19:41 

show 7 more comments

728x90

Why is #define F_CPU have no effect on AVR code _delay_ms_() function?

 

Why is #define F_CPU have no effect on AVR code _delay_ms_() function?

I am programming an ATtiny85 with MS_Visual_Studio with extension Visual_Micro using an Arduino1.6/1.8 Gemma board definition. The programmer is Sparkfun Tiny Programmer. Here is the very simple code

stackoverflow.com

 

 

Viewed 2k times

 

0

I am programming an ATtiny85 with MS_Visual_Studio with extension Visual_Micro using an Arduino1.6/1.8 Gemma board definition. The programmer is Sparkfun Tiny Programmer.
Here is the very simple code utilized. ( Thanks to InsideGadgets YouTube channel " Change the ATtiny85 clock speed on the fly"). It couldn't get any simpler.

Yet, despite the fact that I change the #define F_CPU 1000000 to #define F_CPU 8000000, there is absolutely no effect on the LED flash cycling period, which is about 2 seconds.
The ATtiny85 act as if the clock was 1MHz, despite any changes to F_CPU.
I tested CLKPR = 3 over CLKPR = 0, which changes the prescaler from a factor of 1 to 8.
This should make the delay 8 times longer, which it does. I searched for some details about the F_CPU definition but could not find any explanation for this behavior.

The Question: Why is there no effect on the _delay_ms(1000) after the F_CPU has been defined from 1MHz to 8MHz?

#define F_CPU 1000000 #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> int main(void) { DDRB |= (1 << PB0); while (1) { PORTB |= (1 << PB0); // Toggle LED _delay_ms(1000); // delay 1 second PORTB &= ~(1 << PB0); _delay_ms(1000); // delay 1 second cli(); CLKPR = (1 << CLKPCE); // set for changing prescaler // Change clock prescaler to 0000 CLKPR = 0; // divider by 1 // CLKPR = 3; // divider by 8 sei(); } // complete Loop is a 2 seconds period return 0; }

avrattiny

share  improve this question  follow 

asked Apr 2 '19 at 21:55

Fred Cailloux

1137 bronze badges

  •  

    Are you sure that the macro is actually used during compilation? Where do you define it? You could check the value during runtime and verify that it really is set to what you expect. – Rev1.0 Apr 3 '19 at 9:05

  •  

    try #define F_CPU 8000000UL - note UL at the end. Without it probably functions are treating the value as 16-bit and truncating it, or replacing it with default – AterLux Apr 3 '19 at 11:53

  •  

    Also, make sure the macro is not defined in the compiler options (i.e. there is no-DF_CPU=1000000UL or something like that) – AterLux Apr 3 '19 at 12:00

add a comment

1 Answer

ActiveOldestVotes

0

 

The F_CPU just lets the _delay_ms() macro calculate how many cycles each second takes. You need this because the delay macros are very simple and do not know what the prescaller happens to be set to at the moment they are called at runtime.

So if you are going to be changing the prescaller on the fly, you might want to make two different delay functions so you can make it clear in your code what is going on.

It might look like...

#define F_CPU 1000000 // We start with 8x prescaler on 8Mhz clock #define delay_ms_1Mhz(x) (_delay_ms(x)) // Delay when prescaller set to 8x #define delay_ms_8Mhz(x) (_delay_ms(x*8)) // Delay when prescaller set to 1x so we need to burn 8x as many cycles

...and then decide which to call depending on what the prescaler is set to at that point in your code.

 

 

 

+ Recent posts